c# - .NET Core Custom Authorization Dependency Injection -


we have custom authorization scheme i'm trying solve ability unit test , use dependency injection in .net core. let me explain setup:

i created interface istshttpclient , class stshttpclient. class connects internal web service creates & decodes tokens. has 1 method "decodetoken(string token)" , constructor simple - takes in option object loaded di.

then authorizationhandler in theory use istshttpclient call , decode token. question is, based on examples online don't know how specify/build authorization handler (see code below).

auth code here:

public class myauthorizationrequirement : authorizationhandler<myauthorizationrequirement >, iauthorizationrequirement {     const string bearer = "bearer ";     readonly istshttpclient _client;      public buzzstsauthorizationrequirement([fromservices]istshttpclient client)     {         _client = client;                }      protected override async task handlerequirementasync(authorizationhandlercontext context, mystsauthorizationrequirement requirement)     {         /*  remaining code omitted -  call istshttpclient.decode() */ 

my startup.cs

    public void configureservices(iservicecollection services)     {         services.configure<stshttpoptions>(configuration.getsection("stsconfigurationinfo"));         services.addscoped<istshttpclient , stshttpclient >();         services.addauthorization(options =>         {             options.addpolicy("authorize", policy =>             {                 /* initialize differently?? */                 policy.addrequirements(new mystsauthorizationrequirement( /* somethign needed here?? */));             });         }); 

nicholas,

you have separate handler , requirements here. in addition keep di stuff in handler. requirement going either dto or empty class marker interface iauthorizationrequirement.

requirement:

public class myauthorizationrequirement : iauthorizationrequirement {  } 

handler:

public class myauthorizationhandler : authorizationhandler<myauthorizationrequirement> {     const string bearer = "bearer ";     readonly istshttpclient _client;      public buzzstsauthorizationrequirement([fromservices]istshttpclient client)     {         _client = client;                }      protected override async task handlerequirementasync(authorizationhandlercontext context, myauthorizationrequirement requirement)     {     ...     } } 

configuration:

 services.configure<stshttpoptions>(configuration.getsection("stsconfigurationinfo"));         services.addscoped<istshttpclient , stshttpclient >();         services.addauthorization(options =>         {             options.addpolicy("authorize", policy =>             {                                policy.addrequirements(new myauthorizationrequirement());             });         }); 

Comments