2015-04-04 220 views
3

我在构建基于OWIN的身份验证的基于ASP.NET MVC 5的网站。我在管理员面板的应用程序中创建了一个新的Area。我想有一个不同于普通用户的登录页面。ASP.NET MVC 5 OWIN区域身份验证

例如,当我去http://site/admin/home/index它应该检查授权并重定向到http://site/admin/account/login,而不是去站点用户登录页面。

我已经尝试执行自定义Authorize属性。不过,我不知何故觉得这不是正确的做法。

有人可以建议一个更好或更正确的解决方案吗?

编辑:自定义属性实现

public class AuthorizeAreaAttribute : AuthorizeAttribute 
{ 
    public string Url { get; set; } 

    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      filterContext.HttpContext.Response.Redirect(Url); 
      filterContext.HttpContext.Response.End(); 
     } 
     base.OnAuthorization(filterContext); 
    } 
} 
+0

为什么你认为这不是一个很好的解决方案来通过自定义的授权属性? – tire0011 2015-04-04 09:08:49

+0

@ tire0011,当我使用自定义属性时,碰巧看到一个内部异常被抛出'Headers has already sent!'。 – 2015-04-04 09:18:56

+0

你可以发布自定义属性的代码吗? – tire0011 2015-04-04 09:33:58

回答

1

Configuration方法App_Start/Startup.Auth.cs文件,您可以更改重定向behavoir。

app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
    LoginPath = new PathString("/Account/Login"), 
    Provider = new CookieAuthenticationProvider 
    { 
     // Enables the application to validate the security stamp when the user logs in. 
     // This is a security feature which is used when you change a password or add an external login to your account. 
     OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
      validateInterval: TimeSpan.FromMinutes(30), 
      regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager) 
     ), 

     // Change redirect 
     OnApplyRedirect = ApplyRedirect 
    } 
}); 

private static void ApplyRedirect(CookieApplyRedirectContext context) 
{ 
    Uri absoluteUri; 
    PathString ContentVersioningUrlSegments = PathString.FromUriComponent("/admin/"); 

    if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri)) 
    { 
     PathString remainingPath; 
     var path = PathString.FromUriComponent(absoluteUri); 
     if (path.StartsWithSegments(ContentVersioningUrlSegments, out remainingPath) && remainingPath.HasValue && remainingPath.Value.Length > 1)) 
       context.RedirectUri = "url" + 
        new QueryString(
         context.Options.ReturnUrlParameter, 
         context.Request.Uri.AbsoluteUri); 
    } 

    context.Response.Redirect(context.RedirectUri); 
} 
+0

感谢您的回答。我使用这里提到的方法解决了问题:http://stackoverflow.com/questions/2472578/is-it-possible-to-use-redirecttoaction-inside-a-custom-authorizeattribute-clas它运作良好 – 2015-04-05 15:21:53

+0

只是想不使用自定义属性显示相同的解决方案。 – 2015-04-05 17:40:17