ASP .Net Core身份角色声明未添加到用户 [英] ASP .Net Core Identity Role Claims not adding to User
问题描述
我在使用角色/索赔时遇到问题.
I'm having issues with using Role/Claims.
我已经创建了角色,并给出了角色声明.然后将这些角色分配给用户,根据我在网上阅读的内容,这意味着用户应继承角色声明,但不能继承.该政策无效,经进一步检查,通过JSON输出用户声明时,我看不到声明.
I have created Roles and given the roles claims. Then assigned these roles to the users, from what I read online this means the User should inherit the Role Claims but they don't. The policy's didn't work and upon further inspection I couldn't see the claims when outputting the user claims via JSON.
所有数据都保存在数据库中,如我所见.
All the data is being saved in the database as I can see it.
角色/要求播种者
public static void SeedRolesAndClaims(RoleManager<IdentityRole> roleManager)
{
// Create Roles
IdentityRole adminRole = new IdentityRole("Admin");
roleManager.CreateAsync(adminRole).Wait();
roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "edit.post")).Wait();
roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "delete.post")).Wait();
roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "create.post")).Wait();
roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "view.post")).Wait();
roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "create.comment")).Wait();
IdentityRole userRole = new IdentityRole("User");
roleManager.CreateAsync(userRole).Wait();
roleManager.AddClaimAsync(userRole, new Claim(ClaimTypes.AuthorizationDecision, "create.comment")).Wait();
}
播种者
ApplicationUser user = new ApplicationUser { UserName = "john@email.com", FirstName = "Admin", LastName = "Smith", Email = "john@email.com" };
userManager.CreateAsync(user, "Password123*").Wait();
userManager.AddToRoleAsync(user, "Admin").Wait();
我正在做的检查是
var claims = User.Claims.Select(claim => new { claim.Type, claim.Value }).ToArray();
return Json(claims);
返回身份验证的基本JSON声明
Which returns the basic JSON claims for authentication
[{"type":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier","value":"05bef53e-dd97-41f6-beee-531501cf8598"},{"type":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name","value":"john@email.com"},{"type":"AspNet.Identity.SecurityStamp","value":"SGS23ZGIY6UYOOL2APWRIZKNT2V6QBJC"}]
我不确定是什么问题,并且已经在google/stackoverflow上搜索了一段时间,但没有成功.
I'm not sure what the issue is and have been searching on google/stackoverflow for a while to no prevail.
任何帮助将不胜感激
推荐答案
If you are using .Net Core 2.1 , it seems you will need to change the default Identity configuration according to this issue .
在.Net Core 2.1中,您可以首先创建自己的ApplicationUser
:
In .Net Core 2.1 , you could firstly create your own ApplicationUser
:
public class ApplicationUser : IdentityUser
{
}
修改您的dbcontext:
Modify your dbcontext :
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
使用旧式api配置身份:
Configure the identity using the old-style api :
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
然后将用户和角色设置为种子:
And seed the user and role like :
private async Task CreateUserRoles(IServiceProvider serviceProvider)
{
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
IdentityResult roleResult;
//Adding Admin Role
var roleCheck = await RoleManager.RoleExistsAsync("Admin");
if (!roleCheck)
{
IdentityRole adminRole = new IdentityRole("Admin");
//create the roles and seed them to the database
roleResult = await RoleManager.CreateAsync(adminRole);
RoleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "edit.post")).Wait();
RoleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "delete.post")).Wait();
ApplicationUser user = new ApplicationUser { UserName = "v-nany@hotmail.com", Email = "v-nany@hotmail.com" };
UserManager.CreateAsync(user, "xxxxxx").Wait();
await UserManager.AddToRoleAsync(user, "Admin");
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env ,IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
CreateUserRoles(serviceProvider).Wait();
}
最后,注销并重新登录该帐户,索偿应该在这里:
At last ,logout and re-signin the account , the claim should be there :
如果您使用的是.Net Core 2.0,则您的代码应使用默认的身份模板.
If you are using .Net Core 2.0 , your code should work with the default identity template .
这篇关于ASP .Net Core身份角色声明未添加到用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!