asp.net core - How to configure JwtBearer with mandatory claim? -


my application logic depends on claim existing, hence claim mandatory , needs present in token.

i not interested in authorization policy since policies applies different users , mandatory claim required present in tokens.

right controllers contains:

    private const string mycustomclaim = "foo";     private string _mycustomclaim;      public override void onactionexecuting(actionexecutingcontext context)     {         _mycustomclaim = context.httpcontext.user.findfirst(mycustomclaim)?.value;     } 

if field _mycustomclaim null things fail later. add null check , throw exception, better if authorization middleware did not authorize user if token did not contain claim.

is there way inform authorization middleware claim mandatory?

in startup.cs file when configuring authentication middleware handle ontokenvalidated event.

services.addauthentication(jwtbearerdefaults.authenticationscheme).addjwtbearer(options => {     options.events = new jwtbearerevents     {         ontokenvalidated = context =>         {             const string claimtypefoo = "foo";             if (!context.principal.hasclaim(c => c.type == claimtypefoo))             {                 context.fail($"the claim '{claimtypefoo}' not present in token.");             }             return task.completedtask;         }     }; }); 

this done in class:

file startup.cs

services.addauthentication(jwtbearerdefaults.authenticationscheme).addjwtbearer(options => {     options.events = new myjwtbearerevents(); }); 

file myjwtbearerevents.cs

public class myjwtbearerevents : jwtbearerevents {     private const string claimtypefoo = "foo";      public override task tokenvalidated(tokenvalidatedcontext context)     {         if (!context.principal.hasclaim(c => c.type == claimtypefoo))         {             context.fail($"the claim '{claimtypefoo}' not present in token.");         }          return task.completedtask;     } } 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -