如何获得oauth刷新令牌?

时间:2018-11-29 22:28:27

标签: c# oauth oauth-2.0 access-token

我有一个Web应用程序,该应用程序将Oauth通用化,由于以下错误而无法重用authToken。

{"AADSTS70002: Error validating credentials. AADSTS54005: OAuth2 Authorization 
code was already redeemed, please retry with a new valid code or use an 
existing refresh token.\r\nTrace ID: 30c342a7-f16a-4a05-a4a8- 
c7ee2c722300\r\nCorrelation ID: 3a5c99d1-ca1c-4cd7-bd36- 
cce721bf05b6\r\nTimestamp: 2018-11-21 00:26:18Z"}

我被告知这是一个已知问题/更新herehere。 ...好吧,所以现在我要获取刷新令牌,以便可以重新生成访问令牌,但是我无法正常工作。

我尝试了以下方法: https://docs.microsoft.com/en-us/bingads/shopping-content/code-example-authentication-oauth-当我尝试获取accesstoken或refresh令牌时,该命令似乎无法正常工作并引发异常。说明发生了一个或多个错误。

https://auth0.com/docs/api/authentication#authorization-code-pkce--但不返回刷新令牌。可能是因为我没有code_verifier吗?如果是这样,我将如何获得?

Authorization Code (PKCE) Image

下面是我正在使用的代码示例-这里的问题是我只能使用一次,一旦被重新兑换,由于它已不再存在于缓存中,因此我无法无声地检索它。

ClientCredential clientcred = new ClientCredential(Constants.ClientId, Constants.AppKey);

 TokenCache TC = new TokenCache();

 AuthenticationContext AC = new AuthenticationContext(Constants.Authority, TC);
 //Set token from authentication result
 AuthenticationResult authenticationResult = await AC.AcquireTokenByAuthorizationCodeAsync(
            Constants.Code,
 new Uri(Constants.postLogoutRedirectUri + "Index"), clientcred);

 return authenticationResult.AccessToken;

1 个答案:

答案 0 :(得分:0)

您需要使用 offline_access 范围调用OAuth2授权端点,以获取刷新令牌。

在收到授权码时,您仅应调用AcquireTokenByAuthorizationCodeAsync一次,并且不应使用结果。 azure ad sample

要获取访问令牌时,需要调用AcquireTokenSilently。 azure ad sample

azure ad sample按用户ID使用TokenCache实现。

授权请求 Authorize request

令牌请求 Token request

祝你好运!