因此,我目前已实施IdentityNet 4在.Net核心应用程序中使用JWT承载令牌进行身份验证。Asp.Net核心身份与AuthorizeAttribute不适用于角色
这个问题似乎使用[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]
属性下面是结果:
如此看来,我们连获取用户名或任何关于用户的信息。
即使知道它的工作原理? –
查看'UseIdentityServerAuthentication'内的代码,它调用'UseJwtBearerAuthentication' –