【问题标题】:How to Identify caller when grant_type is client_credentials?当grant_type为client_credentials时如何识别调用者?
【发布时间】:2019-05-25 02:15:49
【问题描述】:

我有 ASP.NET Web 应用程序,并且正在使用 IdentityServer3 进行用户身份验证。我们的客户使用用户名/密码登录 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 项目中,我还需要识别 customer aka caller。根据客户我需要做一些逻辑

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 来识别客户?

【问题讨论】:

    标签: identityserver3


    【解决方案1】:

    实际上我前段时间也有类似的需求。对于最简单的解决方案,您应该能够为您为客户创建的每个 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",
            });
        }
    }
    

    【讨论】:

    • identityserver 中的client 实际上是一个应用程序,在这种情况下我的api 是客户端。所以我在身份服务器中只有一个client。我没有每个呼叫者的多个客户。对于api 客户端,我为每个调用者添加了不同的secret key
    • @LP13 那是不对的。您误解了 OAuth 和客户端凭据流。 Api 是一种资源,访问该资源的实体是客户端。您需要每个客户都有一个客户,而不是每个客户的同一个客户的秘密。
    猜你喜欢
    • 2018-10-04
    • 2022-10-04
    • 1970-01-01
    • 2016-12-31
    • 2016-04-22
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多