Asp.net web api:将未经授权的请求重定向到禁止页面

时间:2017-08-18 09:10:59

标签: c# asp.net angularjs authorization identity

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

这是我的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调用有关...

1 个答案:

答案 0 :(得分:0)

您可以扩展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 与解决方案类似的问题