c# - Get claims from a WebAPI Controller - JWT Token, -


i have built application uses jwt bearer authentication in asp.net core. when authenticating define custom claims need read in webapi controller in order execute actions.

any ideas how can achieve this?

this how code looks like:(code has been simplified)

public async task<iactionresult> authenticateasync([frombody] usermodel user)     {         ..............                  var tokenhandler = new jwtsecuritytokenhandler();                 var key = encoding.ascii.getbytes(_appsettings.secret);                 var tokendescriptor = new securitytokendescriptor                 {                     subject = new claimsidentity(new claim[]                     {                         new claim("usersecuritykey", userdeserialized.securitykey.tostring()),                         new claim("timestamp",timestamp),                         new claim("verificationkey",userdeserialized.verificationkey.tostring())                      }),                     expires = datetime.utcnow.adddays(7),                     signingcredentials = new signingcredentials(new symmetricsecuritykey(key),                         securityalgorithms.hmacsha256signature)                 };                 var token = tokenhandler.createtoken(tokendescriptor);                 var tokenstring = tokenhandler.writetoken(token);       .................                                 } 

another controller: (it needs read "verificationkey" claim.)

    [httpget]     [route("getcandidate")]     public async task<iactionresult> getcandidateasync()     {          try         {              ............                   var verificationkey = //todo: verificationkey token              var verificationrecord = await service.getverificationrecordasync(verificationkey);              .................          }         catch (exception)         {             return notfound();         }     } 

you should able retrieve claims within controller

var identity = httpcontext.user.identity claimsidentity; if (identity != null) {     ienumerable<claim> claims = identity.claims;      // or     identity.findfirst("claimname").value;  } 

if wanted, write extension methods iprincipal interface , retrieve claims using code above, retrieve them using (for example)

httpcontext.user.identity.methodname(); 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -