Yan*_*ang 9 openid oauth-2.0 asp.net-web-api identityserver3 identityserver2
我使用IdentityServer3的资源所有者流,并使用javascript中的用户名和密码将get token请求发送到身份服务器令牌端点,如下所示:
function getToken() {
var uid = document.getElementById("username").value;
var pwd = document.getElementById("password").value;
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
console.log(xhr.status);
console.log(xhr.response);
var response_data = JSON.parse(xhr.response);
if (xhr.status === 200 && response_data.access_token) {
getUserInfo(response_data.access_token);
getValue(response_data.access_token);
}
}
xhr.open("POST", tokenUrl);
var data = {
username: uid,
password: pwd,
grant_type: "password",
scope: "openid profile roles",
client_id: 'client_id'
};
var body = "";
for (var key in data) {
if (body.length) {
body += "&";
}
body += key + "=";
body += encodeURIComponent(data[key]);
}
xhr.setRequestHeader("Authorization", "Basic " + btoa(client_id + ":" + client_secret));
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(body);
}
Run Code Online (Sandbox Code Playgroud)
访问令牌从身份服务器返回,用户通过身份验证.然后我使用此令牌向我的Web Api发送请求.
问题是,当我检查用户是否被分配了角色时,我发现该声明不存在.
[Authorize]
// GET api/values
public IEnumerable<string> Get()
{
var id = RequestContext.Principal as ClaimsPrincipal;
bool geek = id.HasClaim("role", "Geek"); // false here
bool asset_mgr = id.HasClaim("role", "asset_manager"); // false here
return new string[] { "value1", "value2" };
}
Run Code Online (Sandbox Code Playgroud)
以下是在身份服务器中定义客户端的方式.
new Client
{
ClientName = "Client",
ClientId = "client_id",
Flow = Flows.ResourceOwner,
RequireConsent = false,
AllowRememberConsent = false,
AllowedScopes = new List<string>
{
"openid",
"profile",
"roles",
"sampleApi"
},
AbsoluteRefreshTokenLifetime = 86400,
SlidingRefreshTokenLifetime = 43200,
RefreshTokenUsage = TokenUsage.OneTimeOnly,
RefreshTokenExpiration = TokenExpiration.Sliding,
ClientSecrets = new List<Secret>
{
new Secret("4C701024-0770-4794-B93D-52B5EB6487A0".Sha256())
},
},
Run Code Online (Sandbox Code Playgroud)
这就是用户定义的方式:
new InMemoryUser
{
Username = "bob",
Password = "secret",
Subject = "1",
Claims = new[]
{
new Claim(Constants.ClaimTypes.GivenName, "Bob"),
new Claim(Constants.ClaimTypes.FamilyName, "Smith"),
new Claim(Constants.ClaimTypes.Role, "Geek"),
new Claim(Constants.ClaimTypes.Role, "Foo")
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如何向access_token添加声明?非常感谢!
Fra*_*ans 15
我花了一段时间自己解决这个问题.@ leastprivilege对杨的答案的评论有线索,这个答案只是在扩展它.
这完全取决于oAuth和OIDC规范是如何演变的,它不是IdentityServer的人工制品(非常棒).首先,这里是对身份令牌和访问令牌之间差异的相当不错的讨论:https://github.com/IdentityServer/IdentityServer3/issues/2015值得一读.
使用资源所有者流程,就像您一样,您将始终获得访问令牌.默认情况下,根据规范,您不应在该令牌中包含声明(请参阅上面的链接了解原因).但是,在实践中,你可以做到非常好; 它可以节省您在客户端和服务器上的额外工作量.
Leastprivilege所指的是你需要创建一个范围,如下所示:
new Scope
{
Name = "member",
DisplayName = "member",
Type = ScopeType.Resource,
Claims = new List<ScopeClaim>
{
new ScopeClaim("role"),
new ScopeClaim(Constants.ClaimTypes.Name),
new ScopeClaim(Constants.ClaimTypes.Email)
},
IncludeAllClaimsForUser = true
}
Run Code Online (Sandbox Code Playgroud)
然后,当您要求令牌时,您需要请求该范围.即你的线
scope: "openid profile roles",
应改为scope: "member",
(好吧,我说 - 范围在这里发挥双重作用,据我所知 - 它们也是一种控制形式,即客户要求某些范围,如果它是可以被拒绝不允许那些但那是另一个话题).
注意一段时间内我不知道的重要路线,Type = ScopeType.Resource
因为(因为访问令牌是关于控制对资源的访问).这意味着它将应用于访问令牌,并且指定的声明将包含在令牌中(我认为,可能,反对规范,但非常好).
最后,在我的例子中,我既包含了一些特定的声明,也包含了IncludeAllClaimsForUser
明显的愚蠢,但只是想向您展示一些选项.
我发现我可以通过替换 IdentityServerServiceFactory 的默认 IClaimsProvider 来实现此目的。
定制的IClaimsProvider如下:
public class MyClaimsProvider : DefaultClaimsProvider
{
public MaccapClaimsProvider(IUserService users) : base(users)
{
}
public override Task<IEnumerable<Claim>> GetAccessTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, ValidatedRequest request)
{
var baseclaims = base.GetAccessTokenClaimsAsync(subject, client, scopes, request);
var claims = new List<Claim>();
if (subject.Identity.Name == "bob")
{
claims.Add(new Claim("role", "super_user"));
claims.Add(new Claim("role", "asset_manager"));
}
claims.AddRange(baseclaims.Result);
return Task.FromResult(claims.AsEnumerable());
}
public override Task<IEnumerable<Claim>> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, bool includeAllIdentityClaims, ValidatedRequest request)
{
var rst = base.GetIdentityTokenClaimsAsync(subject, client, scopes, includeAllIdentityClaims, request);
return rst;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,像这样替换 IClaimsProvider:
// custom claims provider
factory.ClaimsProvider = new Registration<IClaimsProvider>(typeof(MyClaimsProvider));
Run Code Online (Sandbox Code Playgroud)
结果是,当访问令牌的请求发送到令牌端点时,声明将添加到 access_token。
归档时间: |
|
查看次数: |
13095 次 |
最近记录: |