Azure - AD - AcquireTokenSilent giving error failed_to_acquire_token_silently -
we using azure ad authenticate , refreshed access token every 30 mins. invoke below method acquires security token , add request header.
var userobjectid = claimsprincipal.current.findfirst("http://schemas.microsoft.com/identity/claims/objectidentifier").value; var authcontext = new authenticationcontext(authority, new naivesessioncache(userobjectid)); var credential = new clientcredential(configurationmanager.appsettings["ida:clientid"], configurationmanager.appsettings["ida:clientsecret"]); try { var authenticationresult = authcontext.acquiretokensilent(configurationmanager.appsettings["webapibaseaddress"], credential, new useridentifier(userobjectid, useridentifiertype.uniqueid)); //set cookie azure oauth refresh token - on successful login var httpcookie = httpcontext.current.response.cookies["refreshtoken"]; if (httpcookie != null) httpcookie.value = authenticationresult.refreshtoken; request.headers.authorization = new authenticationheadervalue("bearer", authenticationresult.accesstoken); } catch { //get access token using refresh token var authenticationresult = authcontext.acquiretokenbyrefreshtoken(httpcookie.value, credential, configurationmanager.appsettings["webapibaseaddress"]); }
in above method, have used acquiretokensilent method gives access token. since access token lasts period of time. after expiry, call acquiretokenbyrefreshtoken refresh token.
the above code works well, getting below exception randomly:
microsoft.identitymodel.clients.activedirectory.adalsilenttokenacquisitionexception: failed acquire token silently. call method acquiretoken @ microsoft.identitymodel.clients.activedirectory.acquiretokensilenthandler.sendtokenrequestasync() @ microsoft.identitymodel.clients.activedirectory.acquiretokenhandlerbase.<runasync>d__0.movenext() errorcode: failed_to_acquire_token_silently
what reason of such inconsistent behaviour? same code working on few environments (stage/dev) throwing error randomly on production.
please suggest.
we able resolve this. seems small mistake in code itself. when accesstoken expires, throws exception , tries fetch new 1 using acquiretokenbyrefreshtoken in catch block. here not setting newly received refresh token in cookie. need add below statement in catch block also, refresh token, can passed generate new access token.
httpcookie.value = authenticationresult.refreshtoken;
Comments
Post a Comment