.net-core - 未找到名为“Bearer”的 AuthorizationPolicy
问题描述
尝试将 Jwt 身份验证添加到我的 DotNetCore 2.1 服务器和 Angular 6 应用程序。
我看过很多关于这个话题的文章,似乎没有人会这样做,而且似乎也没有什么对我有用......我不知道出了什么问题......
我得到:'未找到名为:'Bearer' 的 AuthorizationPolicy。当我启动我的服务器...
服务
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:54523",
ValidAudience = "http://localhost:4300",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("tokensecret))
};
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.Build();
});
});
services.AddMvc();
配置
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseMvc();
控制器
[Authorize()]
[Route("api/[controller]")]
public class ProjectController : Controller
如果我使用控制器 [Authorize],当用户未通过身份验证时,它会返回 /Account/Login?ReturnUrl=...
但它是 JWT,它应该只返回 401、403 ......
如果我尝试使用 [Authorize(JwtBearerDefaults.AuthenticationScheme)],我会得到“名为:'Bearer' 的 AuthorizationPolicy 未找到。”
但为什么...
编辑
我不知道那条线正在改变身份验证的行为,但我也使用这条线
serviceCollection.AddIdentity<User, Role>();
怎么了 ?我们不能将 Identity 与 JWT 一起使用?如何为 JWT 配置它?
解决方案
好的,我找到了让它工作的方法......终于!
您需要使用 AddIdentityCore 而不是 AddIdentity。然后需要自己配置,添加AddIdentityCore中没有注册的missings服务。
链接到 AddIdentityCore 方法:https ://github.com/aspnet/Identity/blob/9b385180a9abcb264507efc23279f083bfc50520/src/Core/IdentityServiceCollectionExtensions.cs
身份注册码
var builder = serviceCollection.AddIdentityCore<User>(opt =>
{
opt.Password.RequireDigit = true;
opt.Password.RequiredLength = 8;
opt.Password.RequireNonAlphanumeric = true;
opt.Password.RequireUppercase = true;
opt.Password.RequireLowercase = true;
});
builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
builder.AddEntityFrameworkStores<AmiliaContext>();
builder.AddDefaultTokenProviders();
builder.AddRoleValidator<RoleValidator<Role>>();
builder.AddRoleManager<RoleManager<Role>>();
builder.AddSignInManager<SignInManager<User>>();
serviceCollection.AddDependencies(Assembly.GetExecutingAssembly());
附加说明
用户必须继承 IdentityUser 角色必须继承 IdentityRole
您不能使用 SignInManager 中的 SignInAsync,而需要使用 CheckPasswordSignInAsync。
为什么 ?
因为 SignInAsync 在内部使用 cookie,所以我们不能在 JWT 中使用这种方法。
推荐阅读
- angular - Angular 6路由:同一页面的不同参数
- amazon-web-services - AppSync 检查 DynamoDB 记录是否存在
- html - 第一个孩子增加内容的宽度,直到父边界调用溢出椭圆
- javascript - 使用 requirejs 在 angularjs 中使用 Highcharts 时出错。自定义指令抛出错误
- c# - 是否有默认的默认属性?
- java - 创建事务喜欢使用 EJB 容器管理
- jira-rest-api - 当查询包含空格时如何通过 REST API 检索 Jira 问题
- api - 如何使用 Square API V2 从 Square 检索订单列表
- email - 基于等于今天日期的单元格值发送电子邮件的脚本
- swift - 获取数字 1-5,无论它是什么数字