Azure запрос токена доступа AD - PullRequest
0 голосов
/ 25 марта 2020

В моем приложении WebAssembly Blazor мне нужен доступ к разрабатываемому API и Microsoft.Graph.

Как я понял, я не могу использовать один и тот же токен-носитель для 2 разных ресурсов (мой API и Graph).

Я устанавливаю доступ к своему API с помощью MSAL в Program.cs

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 напрямую, когда мне это нужно ( следующий этот ):

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;
}

Правильно ли подходит? Есть ли лучший?

Должен ли я зарегистрировать 2 IAccessTokenProvider в Program.cs? Как?

У меня проблема в том, что я получаю сообщение об ошибке:

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 голосов
/ 26 марта 2020

Используйте параметры для указания областей, каждый раз, когда вы запрашиваете новый токен:

IAccessTokenProvider authService; /* inject your IAccessTokenProvider */

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