【发布时间】:2017-07-12 13:36:51
【问题描述】:
因此,我目前在 .Net 核心应用程序中实现了 IdentityServer 4,使用 JWT 不记名令牌进行身份验证。
问题似乎出在使用 [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");
}
查看数据库中的所有内容都已正确链接,我可以看到,该用户具有正确的角色,但 Authorize 属性仍然不起作用。
编辑
经过一番调查,当我们拥有[Authorize] 属性时,查看控制器上的User 属性,结果如下:
所以看起来我们甚至没有得到用户名或任何关于用户的信息。
【问题讨论】:
标签: c# asp.net asp.net-core asp.net-identity identityserver4