![](/img/trans.png)
[英]Azure Active Directory in .NET Core 2.2 Web-App | the signature is invalid / signature key was not found
[英]Azure Active Directory Authentication 401, Bearer Token The signature is invalid
我在 .NET CORE 5 中有 Web API 應用程序,在 Angular 10 中有客戶端應用程序。我已在 Azure Active Directory 中注冊這兩個應用程序以進行Authentication
。 我已通過提供用戶憑據在 Angular 應用程序中成功生成令牌,但在進行 API 調用時出現 401 錯誤。 http 響應確認簽名無效。 我嘗試過各種各樣的事情,但沒有運氣。 我在 angular 端使用庫@azure/msal-angular'
www-authenticate: Bearer error="invalid_token", error_description="The signature is invalid"
appsettings.json
AzureAd": {
"Domain": "MyDomain.onmicrosoft.com",
"Tenant": "MyDomain.onmicrosoft.com",
"TanantId": "3xxxxxxx-zzzz-yyyy-bwww-00000000000",
"Instance": "https://login.microsoftonline.com/",
"ClientId": "8f9c5e55-xxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Audience": "8f9c5e55-xxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Issuer": "https://login.microsoftonline.com/3xxxxxxx-zzzz-yyyy-bwww-00000000000/v2.0",
"ResourceId": "https://MyDomain.onmicrosoft.com/8f9c5e55-xxxxxxxxxxxxxxxxxxxx",
"CallbackPath": "/signin-oidc"
Starup.cs
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwtConfig =>
{
jwtConfig.Audience = configuration["AzureAdB2C:ResourceId"];
jwtConfig.Authority = $"{configuration["AzureAdB2C:Instance"]}{configuration["AzureAdB2C:TanantId"]}";
jwtConfig.SaveToken = true;
jwtConfig.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidAudience = jwtConfig.Audience
};
jwtConfig.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = AuthenticationFailed,
OnMessageReceived = OnMessageReceived,
OnTokenValidated = OnTokenValidated
};
});
services.AddCors(options =>
options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
private static Task AuthenticationFailed(AuthenticationFailedContext context)
{
}
private static Task OnMessageReceived(MessageReceivedContext context)
{
}
private static Task OnTokenValidated(TokenValidatedContext arg)
{
}
以下代碼調用 API 以及 header 中的令牌
const myheaders = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.token}`,
});
this.http.get('https://localhost:44362/v2/Site/GetSecureMessage', {headers: myheaders})
.subscribe((data)=>{
console.log(data);
})
}
您需要確保在獲取令牌時使用為 API 定義的 scope 而不是例如“User.Read”。 您似乎收到了 Microsoft Graph API 的訪問令牌,它不適用於您的 API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.