当Grant_type为client_credentials时,如何识别呼叫者?

时间:2018-12-27 00:16:22

标签: identityserver3

我有ASP.NET Web应用程序,并且正在使用IdentityServer3进行用户身份验证。我们的客户使用用户ID /密码登录Web应用程序。 现在,我又有了一个Web API,我们的一些客户需要从他们的应用程序中调用此Web api。 (服务器到服务器的通信)。因此,基于this,我在Identityserver中做了以下

1>创建了一个新的作用域名称api
2>为Web API创建了一个新客户端,并配置了允许的作用域apioffline_access
3>将流设置为ClientCredentials
4>将AccessTokenType设置为Jwt
5> 我为每个客户创建了不同的密钥

现在,我们的客户可以在connect/token端点获取访问令牌,然后使用访问令牌对API进行调用。 API使用IdentityServer验证令牌,然后返回结果。到这里一切都很好。

但是,在API项目中,我还需要标识customercaller。根据客户,我需要做一些逻辑

public class ResourcesController : ApiController
{
    public IHttpActionResult Get()
    {            
        var caller = User as ClaimsPrincipal;
        // need to identify caller here
        return Json(new
        {
            message = "OK",
        });
    }
}

(我想到的一个选择是将客户ID用作API url的一部分。类似http://api.domain.com/v1/customerid/resources之类的东西)

反正有没有利用IdentityServer识别客户的信息?

1 个答案:

答案 0 :(得分:0)

前一段时间,我实际上也有类似的需求。对于最简单的解决方案,您应该能够为您为客户创建的每个Identity Server客户端分配自定义声明。

AlwaysSendClientClaims = true,                     
Claims = new List<Claim>()
{
  new Claim("CustomerId", "0121021") 
}

这些客户声明随后将包含在访问令牌中,因此可以在您的后端使用。

public class ResourcesController : ApiController
{
    public IHttpActionResult Get()
    {            
        var caller = User as ClaimsPrincipal;

        // need to identify caller here
        var customerId = caller?.Claims.Where(p => p.Type.Equals("CustomerId")).First().Value;
        // need to identify caller here

        return Json(new
        {
            message = "OK",
        });
    }
}
相关问题