Override AuthorizeAttribute in ASP.Net Core and respond Json status -


i'm moving asp.net framework asp.net core.

in asp.net framework web api 2 project, can customize authorizeattribute :

public class apiauthorizeattribute : authorizationfilterattribute {     #region methods      /// <summary>     ///     override authorization event custom authorization.     /// </summary>     /// <param name="httpactioncontext"></param>     public override void onauthorization(httpactioncontext httpactioncontext)     {         // retrieve email , password.         var accountemail =             httpactioncontext.request.headers.where(                     x =>                         !string.isnullorempty(x.key) &&                         x.key.equals("email"))                 .select(x => x.value.firstordefault())                 .firstordefault();          // retrieve account password.         var accountpassword =             httpactioncontext.request.headers.where(                     x =>                         !string.isnullorempty(x.key) &&                         x.key.equals("password"))                 .select(x => x.value.firstordefault()).firstordefault();          // account view model construction.         var filteraccountviewmodel = new filteraccountviewmodel();         filteraccountviewmodel.email = accountemail;         filteraccountviewmodel.password = accountpassword;         filteraccountviewmodel.emailcomparision = textcomparision.equal;         filteraccountviewmodel.passwordcomparision = textcomparision.equal;          // find account.         var account = repositoryaccount.findaccount(filteraccountviewmodel);          // account not found.         if (account == null)         {             // treat account unthorized.             httpactioncontext.response = httpactioncontext.request.createresponse(httpstatuscode.unauthorized);              return;         }          // role not defined means request allowed.         if (_roles == null)             return;          // role not allowed          if (!_roles.any(x => x == account.role))         {             // treat account unthorized.             httpactioncontext.response = httpactioncontext.request.createresponse(httpstatuscode.forbidden);              return;         }          // store requester information in action argument.         httpactioncontext.actionarguments["account"] = account;     }      #endregion      #region properties      /// <summary>     ///     repository provides function access account database.     /// </summary>     public irepositoryaccount repositoryaccount { get; set; }      /// <summary>     ///     role can allowed access server.     /// </summary>     private readonly byte[] _roles;      #endregion      #region constructor      /// <summary>     ///     initialize instance default settings.     /// </summary>     public apiauthorizeattribute()     {     }      /// <summary>     ///     initialize instance allowed role.     /// </summary>     /// <param name="roles"></param>     public apiauthorizeattribute(byte[] roles)     {         _roles = roles;     }      #endregion } 

in customized authorizeattribute, can check whether account valid or not , return httpstatuscode message client.

i'm trying samething in asp.net core, no onauthorization me override.

how can achieve same thing in asp.net framework ?

thank you,

you're approaching incorrectly. never encouraged write custom attributes this, or extend existing. asp.net core roles still apart of system backwards compatibility discouraged.

there great 2 part series on of driving architecture changes , way , should utilized found here. if want still rely on roles can so, suggest using policies.

to wire policy following:

public void configureservices(iservicecollection services) {     services.addauthorization(options =>     {         options.addpolicy(nameof(policy.account),                            policy => policy.requirements.add(new accountrequirement()));     }); } 

i created policy enum convenience.

public enum policy { account }; 

decorate entry points such:

[     httppost,     authorize(policy = nameof(policy.account)) ] public async task<iactionresult> postsomething([fromroute] blah) { } 

the accountrequirement placeholder, needs implement iauthorizationrequirement interface.

public class accountrequirement: iauthorizationrequirement { } 

now need create handler , wire di.

public class accounthandler : authorizationhandler<accountrequirement> {     protected override async task handlerequirementasync(         authorizationhandlercontext context,         accountrequirement requirement)     {         // logic here... or else need do.         if (context.user.isinrole("foobar"))         {             context.succeed(requirement);             return;         }     } } 

additional resources


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -