简体   繁体   中英

Azure AD Access Token Request

In my WebAssembly Blazor App, I need to access an API that I'm developing and Microsoft.Graph.

As I understood, I cannot use the same bearer token for 2 different resources (my API and Graph).

I setup the access to my API with MSAL in 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");
});

And I'm trying to get the token for the Graph API directly when I need it (following 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;
}

Is the approach correct? Is there a better one?

Should I register 2 IAccessTokenProvider in Program.cs? How?

The problem I have is that I keep getting the error:

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

How do I setup CORS in my request?

Use the options to specify the scopes, each time you request a new token:

IAccessTokenProvider authService; /* inject your IAccessTokenProvider */

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM