c# - How do you create a custom AuthorizeAttribute in ASP.NET Core? -
i'm trying make custom authorization attribute in asp.net core. in previous versions possible override bool authorizecore(httpcontextbase httpcontext)
. no longer exists in authorizeattribute
.
what current approach make custom authorizeattribute?
what trying accomplish: receiving session id in header authorization. id i'll know whether particular action valid.
i'm asp.net security person. firstly let me apologise none of documented yet outside of musicstore sample or unit tests, , it's still being refined in terms of exposed apis. detailed documentation here.
we don't want writing custom authorize attributes. if need we've done wrong. instead should writing authorization requirements.
authorization acts upon identities. identities created authentication.
you in comments want check session id in header. session id basis identity. if wanted use authorize
attribute you'd write authentication middleware take header , turn authenticated claimsprincipal
. check inside authorization requirement. authorization requirements can complicated like, example here's 1 takes date of birth claim on current identity , authorize if user on 18;
public class over18requirement : authorizationhandler<over18requirement>, iauthorizationrequirement { public override void handle(authorizationhandlercontext context, over18requirement requirement) { if (!context.user.hasclaim(c => c.type == claimtypes.dateofbirth)) { context.fail(); return; } var dateofbirth = convert.todatetime(context.user.findfirst(c => c.type == claimtypes.dateofbirth).value); int age = datetime.today.year - dateofbirth.year; if (dateofbirth > datetime.today.addyears(-age)) { age--; } if (age >= 18) { context.succeed(requirement); } else { context.fail(); } } } }
then in configureservices()
function you'd wire
services.addauthorization(options => { options.addpolicy("over18", policy => policy.requirements.add(new authorization.over18requirement())); });
and apply controller or action method with
[authorize(policy = "over18")]
Comments
Post a Comment