我正在尝试使用Azure AD在.NET Core 3.1 API中实现Bearer令牌(仅)身份验证。
验证authorization_code
后,我能够从Azure AD检索令牌,并且浏览器使用以下命令发布回我的重定向URL:
{"token_type":"Bearer","scope":"User.Read","expires_in":3600,"ext_expires_in":3600,"access_token":"EwBwA8l6...SzT3qoxGbSMg=="}
(缩短)
[一旦有了此令牌,我应该能够直接在我的API上使用[Authorize]
属性,并在标头中使用Bearer令牌进行请求吗?当我这样做时,我会收到401响应。
我在ConfigureServices()
中有这个:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = "<guid>";
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = false,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abc123")),
TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abc123"))
};
});
services.AddControllers();
并且在Configure()
中,我有:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
在我的错误日志中,我看到的消息是:
“承载者”未通过身份验证。失败消息:“没有可用于令牌的SecurityTokenValidator
我已经尝试了Startup.cs中的许多设置组合,无论从Postman调用我的API时,似乎只能得到401。我可以使用在线找到的代码示例进行Cookie身份验证,但我不希望这样做。
令牌是加密的问题吗?我要使用错误的令牌吗?还是还有其他问题?我需要在我的应用程序中为AspNetUser等数据库表设置身份吗?
简而言之,我只是尝试使用Azure AD作为身份验证提供程序来生成Bearer令牌,并通过传入Bearer令牌标头来调用我的API。
有点像您正在尝试在API中使用Microsoft Graph API令牌。 (基于此:"scope":"User.Read"
)
您的前端应用程序需要使用API的作用域,而不是User.Read。这样,它将获得用于您的API的访问令牌。通过“公开API”部分在API应用程序注册中注册范围,并在获取令牌时在前端中使用完整范围值。
您的后端需要以下配置:
.AddJwtBearer(options =>
{
// add v2.0 to the end if your API is set to get v2 tokens in its manifest
options.Authority = "https://login.microsoftonline.com/your-aad-tenant-id";
options.Audience = "your-api-client-id";
});
这应该是身份验证所需的最低配置。启动时,它将自动从授权机构中查找签名密钥等。