【发布时间】:2020-08-12 09:01:59
【问题描述】:
我正在尝试使用 Azure AD 在 .NET Core 3.1 API 中实现不记名令牌(仅)身份验证。
在验证 authorization_code 后,我能够从 Azure AD 中检索令牌,并且浏览器将返回到我的重定向 URL,其中包含以下内容:
{"token_type":"Bearer","scope":"User.Read","expires_in":3600,"ext_expires_in":3600,"access_token":"EwBwA8l6...SzT3qoxGbSMg=="}(缩短)
拥有此令牌后,我是否可以直接在我的 API 上使用 [Authorize] 属性并在标头中使用不记名令牌进行请求?当我这样做时,我会收到 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。
【问题讨论】:
标签: asp.net-core authentication oauth-2.0 jwt azure-active-directory