asp.net-core - 401 使用 Azure AD 在 .NET Core 3.1 中仅使用不记名令牌进行身份验证
问题描述
我正在尝试使用 Azure AD 在 .NET Core 3.1 API 中实现不记名令牌(仅)身份验证。
验证后,我可以从 Azure AD 检索令牌,authorization_code
并且浏览器使用以下内容回发到我的重定向 URL:
{"token_type":"Bearer","scope":"User.Read","expires_in":3600,"ext_expires_in":3600,"access_token":"EwBwA8l6...SzT3qoxGbSMg=="}
(缩短)
拥有此令牌后,我是否可以[Authorize]
直接在我的 API 上使用该属性并在标头中使用 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 作为身份验证提供程序生成承载令牌,并通过传入承载令牌标头来调用我的 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";
});
这应该是身份验证所需的最低配置。它会在启动时自动从权威机构查找签名密钥等。
推荐阅读
- excel - VBA 代码在复制的文件中不再起作用
- html - 按照键入的顺序将 DIV 堆叠在多列中
- c - 在分配的内存上使用 mprotect() 的最便携方式
- jq - 将多个数组中的字段组合到单个对象
- php - 将 php cURL 与 jQuery 一起使用时出现错误消息“不允许使用 405 方法”
- reactjs - 为什么我的 axios 调用即使在解决之后仍返回 undefined?
- python - 在 Python 的正则表达式中为多个条件抓取内部字符串的正确方法是什么
- sql - 从结果集中删除行,其中列对用户只有一个值
- haskell - 在 Haskell 中表示棋盘
- amazon-web-services - 如何自动将 docker 部署到不带 ECS 的 ec2 实例/是否可以使用构建脚本的构建后命令通过 SSH 连接到 EC2 实例?