当前正在更新一些旧的 asp.net 代码,需要通过 AuthorizationCodeCredential for microsoft graph 使用授权代码提供程序。 MS给出了一个例子:https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=csharp#client-credentials-provider。
为了使用此提供程序,我需要获取并传递从重定向返回的授权代码。 这是我不确定如何获取此代码的部分,即使我看到它在浏览器中返回。
// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";
// For authorization code flow, the user signs into the Microsoft
// identity platform, and the browser is redirected back to your app
// with an authorization code in the query parameters
var authorizationCode = "HOW_DO_I_GET_THIS_CODE????";
// using Azure.Identity;
var options = new AuthorizationCodeCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};
// https://learn.microsoft.com/dotnet/api/azure.identity.authorizationcodecredential
var authCodeCredential = new AuthorizationCodeCredential(
tenantId, clientId, clientSecret, authorizationCode, options);
如有任何帮助,我们将不胜感激!
要获取 authorizationCode 值,您需要在浏览器中运行授权请求,要求用户像这样登录:
https://login.microsoftonline.com/tenantId/oauth2/v2.0/authorize?
client_id=appId
&redirect_uri=yourRedirectUri
&response_type=code
&response_mode=query
&scope=User.Read
&state=12345
认证成功后,您将在地址栏中获得授权code值,如下所示:
确保通过从 &state
部分跳过来正确复制
code值,如下所示:
就我而言,我运行了以下示例代码,该代码使用 授权代码 流程通过 Microsoft Graph 获取登录用户详细信息:
using Azure.Identity;
using Microsoft.Graph;
class Program
{
static async Task Main(string[] args)
{
var scopes = new[] { "User.Read" };
var tenantId = "tenantId";
var clientId = "appId";
var clientSecret = "secret";
var authorizationCode = "code_from_above_request";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var authCodeCredential = new AuthorizationCodeCredential(
tenantId, clientId, clientSecret, authorizationCode, options);
var graphClient = new GraphServiceClient(authCodeCredential, scopes);
try
{
var user = await graphClient.Me.GetAsync();
Console.WriteLine("User Information:");
Console.WriteLine($"Name: {user.DisplayName}");
Console.WriteLine($"ID: {user.Id}");
}
catch (ServiceException ex)
{
Console.WriteLine($"Error fetching user profile: {ex.Message}");
}
}
}
回复:
参考:
堆栈内存溢出