gpt4 book ai didi

c# - ASP .Net Core 身份角色声明未添加到用户

转载 作者:行者123 更新时间:2023-11-30 21:30:40 25 4
gpt4 key购买 nike

我在使用角色/声明时遇到问题。

我已经创建了角色并给出了角色声明。然后将这些角色分配给用户,根据我在网上阅读的内容,这意味着用户应该继承角色声明,但他们没有。该政策无效,经过进一步检查,我在通过 JSON 输出用户声明时看不到声明。

如我所见,所有数据都保存在数据库中。

角色/声明播种者

 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 声明

[{"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 上搜索了一段时间但没有成功。

任何帮助将不胜感激

最佳答案

如果您使用的是 .Net Core 2.1,您似乎需要根据 this issue 更改默认身份配置。 .

在 .Net Core 2.1 中,您可以先创建自己的 ApplicationUser:

public class ApplicationUser : IdentityUser
{
}

修改你的数据库上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}

使用旧式 api 配置身份:

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();

然后为用户和角色播种:

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();
}

最后,注销并重新登录帐户, claim 应该在那里:

enter image description here

如果您使用的是 .Net Core 2.0,您的代码应该使用默认标识模板。

关于c# - ASP .Net Core 身份角色声明未添加到用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54064048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com