AcquireTokenAsync failed with UserAssertion in Web API

只谈情不闲聊 提交于 2020-01-06 07:09:01

问题


A Web API has been developed which uses ADAL .Net v3.14 for authentication. Now here is code to get access_token (Using default TokenCache provided by ADAL)

var provider = "https://login.microsoftonline.com/XXXXXXXX.onmicrosoft.com"
var service = "https://XXXXXXXX.onmicrosoft.com/XXXXXXService" //which is registered as service in Azure AD
var clientId  = "01d2b529-XXXX-XXXX-b794-XXXXXXXXXXXX" //client app registered on Azure AD
AuthenticationContext authContext = new AuthenticationContext(provider);
UserPasswordCredential uc = new UserPasswordCredential(user, password);
AuthenticationResult result = authContext.AcquireTokenAsync(service, clientId, uc).ConfigureAwait(false).GetAwaiter().GetResult();

It successfully returns Access_Token. Now After 1hour when this token is expired, I have implemented following code to renew it using Refresh_Token (assuming refresh_token will be taken from cache as implemented ADAL TokenCache) :

  AuthenticationContext authContext = new AuthenticationContext(provider);
  UserAssertion userAssertion = new UserAssertion(oldtoken, "urn:ietf:params:oauth:grant-type:jwt-bearer", upn);
  AuthenticationResult result = authContext.AcquireTokenAsync(resource,clientId, userAssertion).ConfigureAwait(false).GetAwaiter().GetResult();
  var token = result.AccessToken

This code gives error :

"Invalid JWT token. AADSTS50027: Invalid JWT token. Token format not valid".

I checked 'oldtoken' variable, it's valid JWT token.


回答1:


Where do you acquire the access token ? On web api side or client side ?

If you acquire access token on web api side using resource owner password grant flow . And want to renew the access token using refresh token . You just need to use your acquiring token function again since you are acquiring token directly use user's credential .

If you acquire access token on client side , and use that access token to access your web api , then client app should be responsible for checking valid access token and renew access token using refresh token .



来源:https://stackoverflow.com/questions/46645429/acquiretokenasync-failed-with-userassertion-in-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!