我正在编写一个应用程序,该应用程序使用“OAuth 2.0 客户端凭据授予流程”来获取用于调用 Microsoft Graph API 的访问令牌。应用程序以自身身份进行身份验证,而不是代表登录用户进行身份验证。
我的代码基于此来自微软的例子 https://github.com/Azure-Samples/ms-identity-dotnetcore-b2c-account-management/blob/master/src/Program.cs.
这是我初始化 GraphServiceClient 的方式:
// Read application settings from appsettings.json (tenant ID, app ID, client secret, etc.)
AppSettings config = AppSettingsFile.ReadFromJsonFile();
// Initialize the client credential auth provider
var scopes = new[] { "https://graph.microsoft.com/.default" };
var clientSecretCredential = new ClientSecretCredential(config.TenantId, config.AppId, config.ClientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
这就是我后来使用它的方式(例如):
var users = await graphClient.Users.Request().GetAsync();
我的应用程序是一个 API。它不是一个运行一次就完成的应用程序。它将持续运行很长一段时间。所以我担心访问令牌过期后会发生什么。如何确保当我需要使用 graphClient 时访问令牌不会过期?
根据上面的代码片段,我认为您正在使用图SDK https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider并使用客户端凭证流作为身份验证。
所以我们不需要在这里生成访问令牌,而只需使用graphClient
调用图形 api 并收集您需要的信息。并且由于这种模式,它不会出现token expired
情况是每次你调用一个 api 时你都会new clientSecretCredential
在它之前。
让我们回到refresh
,azure ad提供刷新令牌,用于在访问令牌过期时刷新访问令牌,因为刷新令牌的过期时间比访问令牌长得多,当我们尝试获取刷新令牌时,我们需要追加offline_access
到范围当生成访问权限时 https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#successful-response-2。但使用客户端凭据流意味着您的应用程序使用自己的凭据请求新令牌,因此无需使用刷新令牌来避免已登录的用户再次登录。使用凭证流不应返回刷新令牌 https://www.rfc-editor.org/rfc/rfc6749#section-4.4.3.
那么你可能会有一些你坚持使用的想法refresh the expired token
过程,那么你只能先生成一个访问令牌并保存令牌及其过期时间 https://learn.microsoft.com/en-us/dotnet/api/azure.core.accesstoken?view=azure-dotnet#properties在某个地方,并使用访问令牌作为http请求标头并调用graph api。那么代码应该是这样的,但是我认为你不愿意使用这种代码,你也可以参考这个文件 https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-acquire-token?tabs=dotnet更多细节:
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "your_azuread_clientid";
var clientSecret = "corresponding_client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(scopes);
var token = clientSecretCredential.GetTokenAsync(tokenRequestContext).Result.Token;
//using http sender with the token
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token );
// Call the web API.
HttpResponseMessage response = await _httpClient.GetAsync(apiUri);
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)