Mit*_*tch 10 c# .net-core identityserver4
我是 IdentityServer 的新手,我整天都在为这个问题苦苦挣扎。如此之多以至于我几乎要放弃这个。我知道这个问题已经被一遍又一遍地问到,我尝试了许多不同的解决方案,但似乎没有一个有效。希望你能帮助我把我推向正确的方向。
首先,我通过运行安装了 IdentityServer4 模板,dotnet new -i identityserver4.templates并通过运行.is4aspid 模板创建了一个新项目dotnet new is4aspid -o IdentityServer。
之后,我创建了一个新的 IdentityServer 数据库并运行了迁移。到那时,我有了一个默认的 Identity 数据库结构。
在 Config.cs 中,我更改MVC client为以下内容:
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Implicit,
ClientSecrets = { new Secret("47C2A9E1-6A76-3A19-F3C0-S37763QB36D9".Sha256()) },
RedirectUris = { "https://localhost:44307/signin-oidc" },
FrontChannelLogoutUri = "https://localhost:44307/signout-oidc",
PostLogoutRedirectUris = { "https://localhost:44307/signout-callback-oidc" },
AllowOfflineAccess = true,
AllowedScopes = { "openid", "profile", "api1", JwtClaimTypes.Role }
},
Run Code Online (Sandbox Code Playgroud)
并将GetApis方法更改为:
public static IEnumerable<ApiResource> GetApis()
{
return new ApiResource[]
{
new ApiResource("api1", "My API #1", new List<string>() { "role" })
};
}
Run Code Online (Sandbox Code Playgroud)
那里当然数据库中还没有用户,所以我添加了一个注册表并注册了两个虚拟用户,一个使用用户名admin@example.com,一个使用用户名subscriber@example.com。
为了将角色分配给这些用户,我在 Startup.cs 中创建了以下方法。
private async Task CreateUserRoles(IServiceProvider serviceProvider) {
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
IdentityResult adminRoleResult;
IdentityResult subscriberRoleResult;
bool adminRoleExists = await RoleManager.RoleExistsAsync("Admin");
bool subscriberRoleExists = await RoleManager.RoleExistsAsync("Subscriber");
if (!adminRoleExists) {
adminRoleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}
if(!subscriberRoleExists) {
subscriberRoleResult = await RoleManager.CreateAsync(new IdentityRole("Subscriber"));
}
ApplicationUser userToMakeAdmin = await UserManager.FindByNameAsync("admin@example.com");
await UserManager.AddToRoleAsync(userToMakeAdmin, "Admin");
ApplicationUser userToMakeSubscriber = await UserManager.FindByNameAsync("subscriber@example.com");
await UserManager.AddToRoleAsync(userToMakeSubscriber, "Subscriber");
}
Run Code Online (Sandbox Code Playgroud)
在Configure同一类的方法我添加的参数IServiceProvider services和调用上述方法如下所示:CreateUserRoles(services).Wait();。到这个时候,我的数据库确实有两个角色。
接下来,我创建了一个新解决方案(在同一个项目中),并在该解决方案的 Startup.cs 文件中添加了以下内容ConfigureServices。
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options => {
options.SaveTokens = true;
options.ClientId = "mvc";
options.ClientSecret = "32D7A7W0-0ALN-2Q44-A1H4-A37990NN83BP";
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5000/";
options.ClaimActions.MapJsonKey("role", "role");
});
Run Code Online (Sandbox Code Playgroud)
之后我添加了同一个类app.UseAuthentication();的Configure方法。
然后我使用以下 if 语句创建了一个新页面。
if(User.Identity.IsAuthenticated) {
<div>Yes, user is authenticated</div>
}
if(User.IsInRole("ADMIN")) {
<div>Yes, user is admin</div>
}
Run Code Online (Sandbox Code Playgroud)
我登录了,admin@example.com但第二个 if 语句返回False。我通过像这样循环来检查所有声明。
@foreach (var claim in User.Claims) {
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
Run Code Online (Sandbox Code Playgroud)
但是没有找到角色声明,只有 sid、sub、idp、preferred_username 和 name。
我试图在那里获得角色,以便第二个 if 语句返回 True 但在尝试和尝试之后我还没有能够使它工作。有人可以看到我必须做什么才能使这项工作有效吗?我是 IdentityServer4 的绝对初学者,并尽我所能去理解它。任何帮助将不胜感激。提前致谢!
编辑 1:
感谢这个问题和这个问题,我觉得我在正确的轨道上。我做了一些修改,但我仍然无法让它工作。我只是尝试了以下。
public class MyProfileService : IProfileService {
public MyProfileService() { }
public Task GetProfileDataAsync(ProfileDataRequestContext context) {
var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
List<string> list = context.RequestedClaimTypes.ToList();
context.IssuedClaims.AddRange(roleClaims);
return Task.CompletedTask;
}
public Task IsActiveAsync(IsActiveContext context) {
return Task.CompletedTask;
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,我通过添加行在 ConfigureServices 方法中注册了这个类services.AddTransient<IProfileService, MyProfileService>();。之后,我向 GetIdentityResources 方法添加了一个新行,现在看起来像这样。
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource("roles", new[] { "role" })
};
}
Run Code Online (Sandbox Code Playgroud)
我还将角色添加到我的 Mvc 客户端,如下所示: AllowedScopes = { "openid", "profile", "api1", "roles" }。
接下来我切换到另一个项目并在 .AddOpenIdConnect oidc 中添加以下几行。
options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";
Run Code Online (Sandbox Code Playgroud)
但是,我仍然无法让它像我想要的那样工作。有谁知道我错过了什么?
您需要做两件事来确保在声明中获得用户角色:
1-在 IdentityServer4 项目中:您需要实现 IProfileService http://docs.identityserver.io/en/latest/reference/profileservice.html
不要忘记像这样在startup.cs文件中添加类
services.AddIdentityServer()
// I just removed some other configurations for clarity
**.AddProfileService<IdentityProfileService>();**
Run Code Online (Sandbox Code Playgroud)
2- 在 Web Client 项目的 startup.cs 文件中:配置 openId 时,必须提到这一点:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "Identity URL ";
options.RequireHttpsMetadata = true;
options.ClientId = "saas_crm_webclient";
options.ClientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = false;
options.Scope.Add("test.api");
options.Scope.Add("identity.api");
options.Scope.Add("offline_access");
**options.ClaimActions.Add(new JsonKeyClaimAction("role", null, "role"));**
**options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};**
});
Run Code Online (Sandbox Code Playgroud)
使用Edit 1,IdP 配置看起来足以在请求时提供带有角色的身份和访问令牌。剩下的唯一事情是配置客户端以请求访问令牌(.Net 客户端默认情况下不会这样做),或者只是请求身份令牌内的范围。roles
要使用 获得角色id_token,客户端配置必须包括options.Scope.Add("roles");
要获取具有承载令牌的角色,必须通过options.ResponseType = "id_token token";在客户端配置中指定来请求该令牌。
| 归档时间: |
|
| 查看次数: |
12430 次 |
| 最近记录: |