oauth 2.0 - IDX10503: Signature validation failed -


i getting following error valid token after application re-start or publish

idx10503: signature validation failed. keys tried: 'system.identitymodel.tokens.rsasecuritykey exceptions caught: token: '{"typ":"jwt","alg":"rs256","kid":null}.{"unique_name":"test@test.com","iss":"xxxxxx","aud":"xxxxx","exp":1444876186}' 

this function generate key

private void generatersakeys() {     using (rsacryptoserviceprovider rsa = new rsacryptoserviceprovider(2048))     {          key = new rsasecuritykey(rsa.exportparameters(true));         credentials = new signingcredentials (key,securityalgorithms.rsasha256signature, securityalgorithms.sha256digest);         rsa.persistkeyincsp = true;     } } 

this how configuration done

services.configureoauthbearerauthentication(options => {     options.automaticauthentication = true;     options.tokenvalidationparameters.issuersigningkey = generatersakeys();     options.tokenvalidationparameters.validaudience = audience;     options.tokenvalidationparameters.validissuer = issuer;  });  app.usestaticfiles(); app.useoauthbearerauthentication();  // add mvc request pipeline. app.usemvc(); 

and action on controller

// post: /token [httppost()] public async task<iactionresult> token([frombody] loginmodel model) {     if (!modelstate.isvalid)         return httpbadrequest();      jwtsecuritytokenhandler handler = _beareroptions.securitytokenvalidators.oftype<jwtsecuritytokenhandler>().first();      try     {         var user = await _repo.getdetailasync(model.email);         if (!model.password.equals(user.password))             return httpunauthorized();          jwtsecuritytoken securitytoken = handler.createtoken         (             issuer: _beareroptions.tokenvalidationparameters.validissuer,             audience: _beareroptions.tokenvalidationparameters.validaudience,             signingcredentials: _signingcredentials,             subject: new claimsidentity(new claim[] { new claim(claimtypes.name, user.email) }),             expires: datetime.now.addminutes(2)         );          string token = handler.writetoken(securitytoken);          return new objectresult(new tokenmodel() { accesstoken = token, tokentype = "bearer" });      }     catch (exception ex)     {         // todo: add loggin logic here          return httpunauthorized();     }  } 

if you're generating new rsa key each time (re)start server, it's not surprising: tokens signed key a cannot validated using key b. scenario work, need store rsa key somewhere , use same 1 during startup.

one way call rsa.exportparameters(true) , store different parameters somewhere, can retrieve , import them using rsa.importparameters(...).


but best option use aspnet.security.openidconnect.server, automatically generate , store rsa key in last version:

startup.cs

public class startup {     public void configureservices(iservicecollection services) {         services.addauthentication();         services.addcaching();     }      public void configure(iapplicationbuilder app) {         // add new middleware validating access tokens issued oidc server.         app.usejwtbearerauthentication(options => {             options.automaticauthentication = true;             options.authority = "resource_server_1";             options.requirehttpsmetadata = false;         });          // add new middleware issuing tokens.         app.useopenidconnectserver(options => {             options.allowinsecurehttp = true;              options.provider = new openidconnectserverprovider {                 // override onvalidateclientauthentication skip client authentication.                 onvalidateclientauthentication = context => {                     // call skipped() since js applications cannot keep credentials secret.                     context.skipped();                      return task.fromresult<object>(null);                 },                  // override ongrantresourceownercredentials support grant_type=password.                 ongrantresourceownercredentials = context => {                     // credentials validation here.                     // note: can call rejected() message                     // indicate authentication failed.                      var identity = new claimsidentity(openidconnectdefaults.authenticationscheme);                     identity.addclaim(claimtypes.nameidentifier, "todo");                      // default, claims not serialized in access , identity tokens.                     // use overload taking "destination" make sure claims                     // correctly inserted in appropriate tokens.                     identity.addclaim("urn:customclaim", "value", "token id_token");                      var ticket = new authenticationticket(                         new claimsprincipal(identity),                         new authenticationproperties(),                         context.options.authenticationscheme);                      // call setresources list of resource servers                     // access token should issued for.                     ticket.setresources(new[] { "resource_server_1" });                      // call setscopes list of scopes want grant                     // (specify offline_access issue refresh token).                     ticket.setscopes(new[] { "profile", "offline_access" });                      context.validated(ticket);                      return task.fromresult<object>(null);                 }             }         });          app.usemvc();     } } 

project.json

{   "dependencies": {     "microsoft.aspnet.server.weblistener": "1.0.0-rc1-final",     "microsoft.aspnet.mvc": "6.0.0-rc1-final",     "microsoft.aspnet.authentication.jwtbearer": "1.0.0-rc1-final",     "aspnet.security.openidconnect.server": "1.0.0-beta4"   } } 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -