id_token 应该在客户端使用。您可以使用它来访问客户端的声明。AccessToken 将在 API 中使用。
对于要包含在 access_token 中的声明,您需要创建一个包含相关声明的范围并在请求中请求该范围。要创建范围(在自托管示例中将范围添加到 Scopes.cs):
new Scope
{
Name = "myApiScope",
DisplayName = "IdentityManager",
Type = ScopeType.Resource,
Emphasize = true,
ShowInDiscoveryDocument = false,
Claims = new List<ScopeClaim>
{
new ScopeClaim(Constants.ClaimTypes.Name),
new ScopeClaim(Constants.ClaimTypes.Role)
}
}
在您的授权请求中询问范围(在Javascript 隐式客户端中 - 简单如下完成)
function getToken() {
var authorizationUrl = 'https://localhost:44333/core/connect/authorize';
var client_id = 'implicitclient';
var redirect_uri = 'http://localhost:37045/index.html';
var response_type = "token";
var scope = "myApiScope";
var state = Date.now() + "" + Math.random();
localStorage["state"] = state;
var url =
authorizationUrl + "?" +
"client_id=" + encodeURI(client_id) + "&" +
"redirect_uri=" + encodeURI(redirect_uri) + "&" +
"response_type=" + encodeURI(response_type) + "&" +
"scope=" + encodeURI(scope) + "&" +
"state=" + encodeURI(state);
window.location = url;
}
这将在您的访问令牌中包含名称和角色声明
在 Web API 启动中使用相关的中间件配置您的 API(在SampleAspNetWebApi示例中,如下所示)
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions { Authority = " https://localhost:44333/core ", RequiredScopes = new[] { "myApiScope" } });
然后您可以按如下方式访问声明
var principal = User as ClaimsPrincipal;
return from c in principal.Identities.First().Claims
select new
{
c.Type,
c.Value
};