Azure AD访问令牌请求

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

在我的WebAssembly Blazor应用程序中,我需要访问正在开发的API和Microsoft.Graph。

据我了解,我不能对2种不同的资源(我的API和图)使用相同的承载令牌。

我通过Program.cs中的MSAL设置对我的API的访问权限

builder.Services.AddBaseAddressHttpClient();
builder.Services.AddMsalAuthentication(options =>
{
    var authentication = options.ProviderOptions.Authentication;
    authentication.Authority = "https://login.microsoftonline.com/xxx";
    authentication.ClientId = "xxx";
    options.ProviderOptions.DefaultAccessTokenScopes.Add("xxx/user_impersonation");
});

并且我正在尝试在需要时直接获取Graph API的令牌(this之后:

internal class Token
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }
}

private static async Task<Token> GetElibilityToken(HttpClient client)
{
    string baseAddress = @"https://login.microsoftonline.com/xxx/oauth2/v2.0/token";

    string grant_type = "authorization_code";
    string client_id = "xxx";
    string client_secret = "==xxx";
    string scope = "https://graph.microsoft.com/.default";

    var form = new Dictionary<string, string>
        {
            {"grant_type", grant_type},
            {"client_id", client_id},
            {"client_secret", client_secret},
            {"scope", scope }
        };

    HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
    var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
    Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
    return tok;
}

该方法正确吗?有更好的吗?

我应该在Program.cs中注册2 IAccessTokenProvider吗?怎么样?

我的问题是我不断收到错误:

Access to fetch at 'https://login.microsoftonline.com/xxx/oauth2/v2.0/token' from origin 'https://localhost:xxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
dotnet.3.2.0-preview2.20159.2.js:1 POST https://login.microsoftonline.com/xxx/oauth2/v2.0/token net::ERR_FAILED

如何在我的请求中设置CORS?

c# azure-active-directory microsoft-graph webassembly blazor-client-side
1个回答
0
投票

每次请求新令牌时,请使用选项指定范围:

IAccessTokenProvider authService; /* inject your IAccessTokenProvider */

var tokenResult = await authService .RequestAccessToken(
    new AccessTokenRequestOptions
    {
        ReturnUrl = "...",
        Scopes = new string[] { "..." }
    });
© www.soinside.com 2019 - 2024. All rights reserved.