因此,我目前已實施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' –