sha*_*non 4 asp.net authentication asp.net-mvc forms-authentication authorize-attribute
什么是直接返回401和登录页面的简单方法,避免302重定向,当IAuthorizationFilterIIS 7.0上的ASP.NET MVC 5应用程序出现故障时,我必须实现哪些基础设施才能使其工作?
可能的替代问题:这是个坏主意吗?
-
我实现了Application_EndRequest()垫片来解决由AJAX引起的问题FormsAuthentication.它转换所有401 UNAUTHORIZEDTO 302 FOUND(即重定向).但是,这会导致其他问题,因为现在所有 302重定向都转换为401.因此,要解决此修复程序,我摆脱了重定向为500 SERVER ERROR,和404 NOT FOUND,我觉得有几个还是我错过了...
也许我过度设计了这个,但是在这个练习之后,首先返回302为401是不正确的.解决了一个问题,创造了新问题.我认为技术上理想的答案是处理401就地.然后服务器发送一个诚实的状态代码,无论是否AJAX,如果AJAX客户端收到登录HTML,没有什么大不了的.
-
使用不带FormsAuthentication的FormsAuthentication cookie
我尝试了一种方法,使用:
<httpErrors errorMode="Custom" existingResponse="Replace">
<error statusCode="401" responseMode="ExecuteURL" path="/Account/AuthReq" />
</httpErrors>
Run Code Online (Sandbox Code Playgroud)
然而,为了使这项工作我不得不退出FormsAuthentication的Web.config,当我拉出来的窗体身份验证,我的自定义AuthorizeAttribute停止运行.我认为FormsAuthentication我实际使用的代码很少,但我有点害怕摆脱它,因为我不想将自己的无知应用于管理安全的身份验证cookie.
据我所知,FormsAuthentication如果我不想要401 - > 302处理,下面的代码代表了我目前唯一依赖的地方.
/// <summary>
/// Stores this SessionIdentity in the Forms Authentication token for use next request
/// </summary>
public void Write(HttpContext httpContext) {
httpContext.Response.AppendCookie(FormsAuthentication.GetAuthCookie(serialize(), false));
}
/// <summary>
/// Constructs a SessionIdentity from the Forms Authentication token
/// </summary>
public static SessionIdentity Read(HttpContext httpContext) {
IIdentity identity = httpContext.User.Identity;
return identity.IsAuthenticated
? deserialize(identity.Name)
: Unauthenticated;
}
/// <summary>
/// Removes the SessionIdentity Forms Authentication token for the next request
/// </summary>
public static void Clear(HttpContext httpContext) {
var clearAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
clearAuthCookie.Expires = DateTime.Now.AddYears(-1);
httpContext.Response.Cookies.Add(clearAuthCookie);
}
Run Code Online (Sandbox Code Playgroud)
我似乎可以避免在Web.Config中依赖FormsAuthentication,并且仍然可以使用OEM加密票证,只需通过利用FormsAuthentication.Decrypt()而不是HttpContext.User.Identity我在上面的位置.我还没有调查这个改变是否与相当新的基于声明的票证或MVC5中新的AuthenticationFilter有关.
使用AppHarbor的.NET开放式身份验证库
虽然我不确定它对我的场景是否正确,但是这里对类似主题的一些答案已经声明不可能禁用FormsAuthentication的302重定向动作.但是,很明显,ASP.NET中没有包含备用身份验证机制.
Dar*_*rov 12
检查SuppressFormsAuthenticationRedirect房产.
然后编写自定义Authorize属性:
public class MyAuthorizeAttribute: AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Account/Login.cshtml",
};
}
}
Run Code Online (Sandbox Code Playgroud)
可用于装饰受保护的控制器/动作:
[MyAuthorize]
public ActionResult Admin()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
显然,如果您不希望它们接管,您可能还想删除web.config中401个状态代码的任何自定义错误页面.
| 归档时间: |
|
| 查看次数: |
2055 次 |
| 最近记录: |