[英]Adding custom Claim for access in API with IdentityServer4
I'm trying to work with a application to use IdentityServer4, it has the basic setup of the identity server, MVC client, and web API. 我正在尝试使用一个应用程序来使用IdentityServer4,它具有身份服务器,MVC客户端和Web API的基本设置。
I have a custom Profile service (which I've registered in Startup.cs) where I'm adding a custom claim, here's my GetProfileDataAsync
method: 我有一个自定义配置文件服务(已在Startup.cs中注册),在其中添加自定义声明,这是我的GetProfileDataAsync
方法:
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var user = _userManager.GetUserAsync(context.Subject).Result;
var claims = new List<Claim>
{
new Claim("TestFullName", user.FullName),
};
context.IssuedClaims.AddRange(claims);
return Task.FromResult(0);
}
My problem is that when I log into the identity server, I can see the additional claim - but when I call my API from the MVC app, my custom claim isn't there. 我的问题是,当我登录到身份服务器时,可以看到其他声明-但是,当我从MVC应用程序调用API时,我的自定义声明不存在。 Here's the code in my MVC app to call the API: 这是我的MVC应用程序中调用API的代码:
public async Task<IActionResult> ClientAuthorizedAPICall(string token)
{
// discover endpoints from metadata
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
// request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("testAPI");
// call api
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
...
}
And the method on my API is simply: 我的API上的方法很简单:
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
Am I doing something wrong? 难道我做错了什么? Or should I be doing something different instead of using User.Claims
? 还是我应该做其他事情,而不是使用User.Claims
?
Like rawel's comment says, you'll want to use the MVC app user's access token to make your API call. 就像rawel的评论所说,您将要使用MVC应用程序用户的访问令牌来进行API调用。 It would look something like this: 它看起来像这样:
// get the current user's access token
var accessToken = await HttpContext.GetTokenAsync("access_token");
// call api
var client = new HttpClient();
client.SetBearerToken(accessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
You can see a similar approach in the quickstart on hybrid flow . 您可以在混合流快速入门中看到类似的方法。
To get your custom user claim into the access token for your API, you'll need to include it when defining the API resource. 为了使自定义用户声明进入API的访问令牌,您需要在定义API资源时将其包括在内。 For example: 例如:
new ApiResource("testAPI", "Test API", new[] { "TestFullName" }),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.