Azure AD访问令牌请求



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

正如我所理解的,我不能对两个不同的资源(我的API和Graph(使用相同的承载令牌。

我在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的令牌(如下(:

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?

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

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

最新更新