繁体   English   中英

ASP.NET Web API:将未经授权的请求重定向到禁止页面

[英]Asp.net web api : redirect unauthorized requst to forbidden page

我试图将未经授权的请求重定向到某些禁止的页面,但是我在响应正文中得到了禁止的页面,我该如何解决呢?

这是我的StartUp类:

app.CreatePerOwinContext(StoreContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
     ExpireTimeSpan = TimeSpan.FromDays(30),
});

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

我试图达到的方法是:

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public string GetCurrentUsername()
    {
        return UserManager.FindByEmail(User.Identity.Name).Name;
    }

我已经尝试过这个东西:

  • 从cookieOptions中删除LoginPath以返回401
  • 创建自定义授权属性

顺便说一句,即时通讯使用Angular,我认为这个问题与Ajax呼叫有关...

您可以扩展authorize属性以指定禁止页面。 像这样的东西:

添加一个名为AuthorizationAttribute的新类,该类继承自AuthorizeAttribute类。 然后覆盖2种方法

public class AuthorizationAttribute : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
      //check if user in in role admin and if yes then return true, else return false. Once it returns false, then HandleUnauthorizedRequest will be triggered automatically
      return userManager.IsUserInAdminRole(username);
   }

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
      filterContext.Result = new RedirectResult("~/Error/ForbiddenPage");
   }
}

在您的方法中,使用新的AuthorizationAttribute类:

    [HttpGet]
    [Authorization] //You can just write Authorization without the word Attribute
    public string GetCurrentUsername()
    {
        return UserManager.FindByEmail(User.Identity.Name).Name;
    }

如果与您的ajax有关,则可以在这里找到: github.com/ronnieoverby/mvc-ajax-auth与解决方案类似的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM