2017-07-12 98 views
0

因此,我目前已實施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]屬性下面是結果: enter image description here

如此看來,我們連獲取用戶名或任何關於用戶的信息。

回答

0

我想你可能會在你的Configuration方法中缺少UseJwtBearerAuthentication

app.UseJwtBearerAuthentication(new JwtBearerOptions() 
{ 
    TokenValidationParameters = new TokenValidationParameters() 
    { 
     // You can set different kind of validations here. 
     // ValidateIssuerSigningKey, ValidateAudience, ValidateIssuer, etc. 
    } 
}); 
+0

即使知道它的工作原理? –

+0

查看'UseIdentityServerAuthentication'內的代碼,它調用'UseJwtBearerAuthentication' –

0

看着你提供的圖像,看起來你在你的索賠列表中有20個索賠。試着看看你在該列表中看到了哪些角色/聲明!

使用`[授權的]`只是沒有當我提供了一個角色時,你可以得到列表中

var claims = HttpContext.User.Claims.ToList(); 

foreach (var c in claims) 
{ 
    Console.WriteLine(c.Type + c.Value); 
}