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


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

here's 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 im trying reach :

    [httpget]     [authorize(roles = "admin")]     public string getcurrentusername()     {         return usermanager.findbyemail(user.identity.name).name;     } 

i have tried things :

  • remove loginpath cookieoptions return 401
  • create custom authorize attribute

by way im using angular , think issue related ajax call ...

you can extend authorize attribute specify forbidden page. this:

add new class named authorizationattribute inherits authorizeattribute class. , override 2 methods

public class authorizationattribute : authorizeattribute {    protected override bool authorizecore(httpcontextbase httpcontext)    {       //check if user in in role admin , if yes return true, else return false. once returns false, handleunauthorizedrequest triggered automatically       return usermanager.isuserinadminrole(username);    }     protected override void handleunauthorizedrequest(authorizationcontext filtercontext)    {       filtercontext.result = new redirectresult("~/error/forbiddenpage");    } } 

and in method, use new authorizationattribute class:

    [httpget]     [authorization] //you can write authorization without word attribute     public string getcurrentusername()     {         return usermanager.findbyemail(user.identity.name).name;     } 

if related ajax, find here: github.com/ronnieoverby/mvc-ajax-auth similar problem solution


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -