ASP.NET MVC 5 OWIN区域身份验证

时间:2015-04-04 08:59:48

标签: asp.net-mvc authentication owin area

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

例如,当我转到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);
    }
}

1 个答案:

答案 0 :(得分:1)

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

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);
}