简体   繁体   中英

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

im trying to redirect unauthorized request to some forbidden page but instead i'm getting forbidden page in response body , how can i fix this ?

Here's my StartUp class :

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

The method which im trying to reach is :

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

i have tried this things :

  • remove LoginPath from cookieOptions to return 401
  • create custom authorize attribute

by the way im using Angular , i think this issue is related to ajax call ...

you can extend the authorize attribute to specify the forbidden page. something like this:

Add a new class named AuthorizationAttribute which inherits from the AuthorizeAttribute class. and then override the 2 methods

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

And in your method, use the new AuthorizationAttribute class:

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

If it is related to your ajax, you find here: github.com/ronnieoverby/mvc-ajax-auth a similar problem with solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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