Azure AD访问令牌请求

时间:2020-03-24 22:42:09

标签: c# azure-active-directory microsoft-graph-api webassembly blazor-client-side

在我的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?

1 个答案:

答案 0 :(得分:0)

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

IAccessTokenProvider authService; /* inject your IAccessTokenProvider */

var tokenResult = await authService .RequestAccessToken(
    new AccessTokenRequestOptions
    {
        ReturnUrl = "...",
        Scopes = new string[] { "..." }
    });