【问题标题】:ASP.NET MVC 5 OWIN Area AuthenticationASP.NET MVC 5 OWIN 区域认证
【发布时间】:2015-06-09 06:33:18
【问题描述】:

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

【问题讨论】:

  • 为什么您认为遍历自定义 Authorize 属性不是一个好的解决方案?
  • @tire0011,我碰巧看到在使用自定义属性时抛出了一个内部异常Headers were already sent!
  • 您可以发布自定义属性中的代码吗?

标签: asp.net-mvc authentication owin area


【解决方案1】:

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

【讨论】:

  • 感谢您的回答。我使用这里提到的方法解决了这个问题:stackoverflow.com/questions/2472578/… 并且效果很好
  • 只想在不使用自定义属性的情况下显示相同的解决方案。
猜你喜欢
  • 2014-01-02
  • 2023-03-23
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 2011-03-18
  • 2014-11-21
  • 1970-01-01
相关资源
最近更新 更多