[英]Get refresh token additionally to access token with Microsoft.Identity.Client
我使用了几个属性,如租户 ID、客户端 ID、客户端密码、重定向 uri 和为用户生成的授权代码。 我需要获取访问和刷新令牌,但 API 不会返回任何类似刷新令牌的内容。 除了访问令牌之外,我还需要一个刷新令牌并及时到期。 我使用以下代码:
ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions();
options.ClientId = clientId;
options.TenantId = tenantId;
options.ClientSecret = clientSecret;
options.RedirectUri = redirectUri;
ConfidentialClientApplicationBuilder builder = ConfidentialClientApplicationBuilder.
CreateWithApplicationOptions(options);
IConfidentialClientApplication app = builder.Build();
AcquireTokenByAuthorizationCodeParameterBuilder acquireTokenBuilder =
app.AcquireTokenByAuthorizationCode(ServiceConstants.ALL_SCOPE_AUTHORIZATIONS.Split(' '), authorizationCode);
AuthenticationResult result = await acquireTokenBuilder.ExecuteAsync();
string accessToken = result.AccessToken;
// NO string refreshToken = result.RefreshToken
这很奇怪,因为在几个示例中,我看到 AuthenticationResult 中有可用的 RefreshToken,但在我的示例中却没有。 你知道为什么吗? 以及如何获得刷新令牌?
因为在那之后我需要在到期时刷新访问令牌,而我只有访问令牌、租户 ID、客户端 ID、秘密(或证书)和重定向 URI。 顺便说一句,访问令牌过期后如何重新生成它?
非常感谢和最好的问候
阿德里安
您需要检查在/authorize
和/token
请求中作为ServiceConstants.ALL_SCOPE_AUTHORIZATIONS传递的内容。 范围列表应包含offline_access
scope,因为它告诉 Azure 您的应用程序需要刷新令牌才能扩展对资源的访问。
刷新令牌的生命周期比访问令牌长,因此只要您的访问令牌过期,您就可以再次调用/token
端点,提供先前收到的刷新令牌并使用参数grant_type=refresh_token
。
我试图在我的环境中重现相同的内容并得到如下结果:
我创建了一个Azure AD 应用程序并添加了 API 权限:
请注意:要获取刷新令牌,请确保在您的 Azure AD 应用程序中授予
offline_access
API 权限,并在生成访问令牌时将其包含在scope中。
我在 Postman 中使用以下参数生成了访问和刷新令牌:
GET https://login.microsoftonline.com/TenantId/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
scope:https://graph.microsoft.com/.default offline_access
grant_type:authorization_code
redirect_uri:RedirectUri
code:code
要在您的代码中获取此内容,您可以包含以下行:
refreshToken = result.RefreshToken
为了刷新访问令牌,我使用了如下参数:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientId
grant_type:refresh_token
refresh_token:refreshtoken
client_secret:ClientSecret
示例代码:
AzureADApp.AcquireTokenByRefreshToken(RefreshToken, scope) .ExecuteAsync();
var refreshedAccessToken = result.AccessToken;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.