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

3
我正在构建一个基于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);
    }
}

你为什么认为通过自定义授权属性不是一个好的解决方案? - tire0011
@tire0011,我在使用自定义属性时遇到了一个内部异常被抛出的情况,“Headers were already sent!”(头信息已经发送!)。 - Babu James
你能把自定义属性的代码贴出来吗? - tire0011
1个回答

2
App_Start/Startup.Auth.cs 文件的 Configuration 方法中,您可以更改重定向行为。
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);
}

感谢您的回答。我使用了这里提到的方法解决了问题:https://dev59.com/R3E95IYBdhLWcg3wEpvo,现在它运行良好。 - Babu James
只想展示相同的解决方案,而不使用自定义属性。 - Mohsen Esmailpour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接