【发布时间】:2020-02-27 16:52:25
【问题描述】:
我正在学习如何在 ASP 中使用 JWT 令牌认证。我有一个简单的网站,其中包含 CRUD 操作和一个存储库,我添加了注册/登录功能,并且我有一个名为“管理员”的超级用户角色。通常,这是我检查用户当前是否以管理员身份登录的方式:
bool admin = User.IsInRole(Constants.ADMIN_ROLE);
在我将 JWT 身份验证添加到我的应用程序之前,此功能运行良好。现在,使用我的管理员帐户(手动添加到数据库)登录,我从来没有得到正确的值。当我尝试查询用户时,我得到 NULL:
var user = await _userManager.GetUserAsync(HttpContext.User)
这是我在 Startup.cs 中的 ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddIdentity<MyUser, MyRole>()
.AddEntityFrameworkStores<MyContext>()
.AddRoles<MyRole>();
services.AddDbContext<MyContext>(builder =>
{
builder.UseSqlServer(Configuration["ConnectionStrings"]);
});
// repo code here ommitted for clarity
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
};
});
}
这是我的配置类:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
}
据了解,由于 JWT 是身份验证,它根本不应该影响授权,所以我想我忘了使用一些额外的选项,但我似乎找不到什么。任何帮助表示赞赏!
【问题讨论】:
标签: asp.net-core asp.net-core-webapi asp.net-authorization jwt-auth