如何检索与 AuthorizationCodeCredential 一起使用的身份验证代码

问题描述 投票:0回答:1

当前正在更新一些旧的 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);

如有任何帮助,我们将不胜感激!

azure microsoft-graph-api asp.net-core-8 microsoft-identity-web
1个回答
0
投票

要获取 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

enter image description here

认证成功后,您将在地址栏中获得授权code值,如下所示:

enter image description here

确保通过从 &state 部分跳过来正确复制

code
值,如下所示:

enter image description here

就我而言,我运行了以下示例代码,该代码使用 授权代码 流程通过 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}");
        }
    }
}

回复:

enter image description here

参考:

如何在 MS Graph API 6.12 中获取授权代码 - me

堆栈内存溢出
© www.soinside.com 2019 - 2024. All rights reserved.