【发布时间】:2019-06-10 02:06:52
【问题描述】:
史前史:
我使用 IdentityServer4 为微服务开发身份验证和授权,但在授权方面存在问题。
我有两个服务:
- 使用 identityserver4 服务,这是我的身份验证服务
- 测试 MVC 项目
我成功连接了这些服务并使用了混合流,身份验证工作成功,我的角色也工作了,因为我在身份验证服务端使用自定义 ProfileService 将角色包含在 JWT 令牌中。
问题情况:
1.用户没有任何身份验证令牌。尝试在 MVC 站点上使用 [Authorize(Roles = "Admin")] 属性打开页面并重定向到 Auth 服务上的页面。
2. 用户输入登录名和密码。
3. 获得 Role=Admin 的令牌,在 Auth 服务上重定向回 MVC 站点。
4. 为用户打开的页面,因为他具有管理员角色。
5. 从身份验证服务的管理员角色中删除用户。
6. 重新加载页面并再次为该用户打开页面,这是正确的,因为在令牌中他具有角色管理员。
问题:在身份验证服务端更改角色或声明后如何实现令牌?
身份服务器配置:
public static IEnumerable<Client> GetClients()
{
return new Client[]
{
new Client
{
ClientId = "Epp.Web.Mvc",
ClientName = "Единый Портал Потребителей",
AllowedGrantTypes = new List<string>{GrantType.Hybrid},
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
RequireConsent = false,
AllowAccessTokensViaBrowser = true,
AlwaysIncludeUserClaimsInIdToken = true,
AlwaysSendClientClaims = true,
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"epp",
"roles"
},
RedirectUris = new List<string>
{
"http://localhost:5002/signin-oidc",
"https://localhost:5003/signin-oidc"
},
PostLogoutRedirectUris = new List<string>{ "http://localhost:5002/signout-callback-oidc" },
AccessTokenLifetime = 60 * 10
}
};
}
MVC 启动:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromHours(2))
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "https://localhost:5001";
options.ClientId = "Epp.Web.Mvc";
options.ResponseType = "code id_token";
options.ClientSecret = "secret";
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
options.RequireHttpsMetadata = false;
options.Scope.Add(IdentityServerConstants.StandardScopes.OpenId);
options.Scope.Add(IdentityServerConstants.StandardScopes.Profile);
options.Scope.Add("epp");
options.Scope.Add("roles");
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
});
【问题讨论】:
-
不要实现你的代币,撤销它们并发行一个新的
-
这就是为什么现在要避免基于角色的授权,并且首选基于范围的授权,例如
service1.read, service2.full_access范围。您可以:将基于角色的授权转移到每个服务中并远离身份服务器,转换为基于范围的授权。
标签: c# asp.net-mvc authorization identityserver4 roles