所以我目前使用JWT承载令牌在.Net核心应用程序中实现了IdentityServer 4.进行身份验证。
问题似乎是在使用[Authorize(Roles = "Admin")]
时我从日志中获得以下内容:[Information] AuthenticationScheme: "Bearer" was forbidden.
当我只有[Authorize]
属性时,它可以正常工作。
以下是代码:
services.AddDbContext<OmbiContext>(options =>
options.UseSqlite("Data Source=Ombi.db"));
services.AddIdentity<OmbiUser, IdentityRole>()
.AddEntityFrameworkStores<OmbiContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
.AddInMemoryApiResources(IdentityConfig.GetApiResources())
.AddInMemoryClients(IdentityConfig.GetClients())
.AddAspNetIdentity<OmbiUser>();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 1;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
});
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMemoryCache cache)
{
app.UseIdentity();
app.UseIdentityServer();
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = options.Value.WebsiteUrl,
ApiName = "api",
ApiSecret = "secret",
EnableCaching = true,
CacheDuration = TimeSpan.FromMinutes(10), // that's the default
RequireHttpsMetadata = options.Value.UseHttps, // FOR DEV set to false
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
// etc...
}
创建用户和角色的代码:
var result = await UserManager.CreateAsync(userToCreate, user.Password);
if (result.Succeeded)
{
if (!(await RoleManager.RoleExistsAsync("Admin")))
{
var r = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}
var re = await UserManager.AddToRoleAsync(userToCreate, "Admin");
}
查看数据库中的所有内容都已正确链接,我可以看到,该用户具有正确的角色,但“授权”属性仍无效。
修改
经过一番调查后,当我们在User
属性处时,查看控制器上的[Authorize]
属性是结果:
所以看起来我们甚至没有得到用户的用户名或任何内容。
答案 0 :(得分:0)
我认为您UseJwtBearerAuthentication
方法中可能遗漏了Configuration
。
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
TokenValidationParameters = new TokenValidationParameters()
{
// You can set different kind of validations here.
// ValidateIssuerSigningKey, ValidateAudience, ValidateIssuer, etc.
}
});
答案 1 :(得分:0)
查看您提供的图片,看起来您的索赔清单中有20件索赔。试着看看你在列表中看到了什么角色/声明!
您可以通过
获取列表var claims = HttpContext.User.Claims.ToList();
foreach (var c in claims)
{
Console.WriteLine(c.Type + c.Value);
}