简体   繁体   English

使用Client Credentials流持久化令牌的最佳实践

[英]Best practice for persisting tokens using Client Credentials flow

I have an ASP.NET Core MVC application allowing anonymous users. 我有一个允许匿名用户的ASP.NET核心MVC应用程序。 This app is calling an ASP.NET Web API that is protected by Identity Server 4. I have created a client in Identity Server describing the MVC app (client) and given it access to the api scope like this: 这个应用程序调用受Identity Server 4保护的ASP.NET Web API。我在Identity Server中创建了一个描述MVC应用程序(客户端)的客户端,并允许它访问api作用域,如下所示:

new Client
{
    ClientId = "my-mvc-client-app",
    AllowedGrantTypes = GrantTypes.ClientCredentials,

    RequireConsent = false,
    ClientSecrets = new List<Secret> { new Secret("this-is-my-secret".Sha256()) },
    AllowedScopes = new List<string>
    {
        StandardScopes.OpenId.Name,
        StandardScopes.Profile.Name,
        StandardScopes.OfflineAccess.Name,
        "my-protected-api"
    },
    RedirectUris = new List<string>
    {
        "http://localhost:5009/signin-oidc",
    }
}

In my MVC app, I'm using TokenClient to get a token that I can use when making requests to the protected API like this: 在我的MVC应用程序中,我正在使用TokenClient获取一个令牌,我可以在向受保护的API发出请求时使用TokenClient的令牌:

var disco = await DiscoveryClient.GetAsync("http://localhost:5010");
var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("hrmts-test-candidate-api-scope");

This works fine, but I'm requesting new tokens from Identity Server on every request, which is probably not a good idea. 这工作正常,但我在每次请求时都要求Identity Server提供新令牌,这可能不是一个好主意。

What is the best practice for handling the tokens? 处理令牌的最佳做法是什么? How can I persist them on the client (the MVC app) and how can I handle refresh tokens to make sure the client gets a new token when necessary? 如何在客户端(MVC应用程序)上保留它们以及如何处理刷新令牌以确保客户端在必要时获取新令牌?

You need to wrap that client in a managed service of some kind (as a singleton) so that you can use it anywhere you need. 您需要将该客户端包装在某种托管服务中(作为单例),以便您可以在任何需要的地方使用它。 We have a token component that we use for server to server communication that follows this flow: 我们有一个令牌组件,用于遵循此流程的服务器到服务器通信:

public class ServerTokenComponent
{
    private TokenResponse Token { get; set; }
    private DateTime ExpiryTime { get; set; }
    public async Task<TokenResponse> GetToken()
    {
        //use token if it exists and is still fresh
        if (Token != null && ExpiryTime > DateTime.UtcNow)
        {    
            return Token;
        }     

        //else get a new token
        var client = new TokenClient("myidpauthority.com","theclientId","thesecret")
        var scopes = "for bar baz";

        var tokenResponse = await client.RequestClientCredentialsAsync(scopes);

        if (tokenResponse.IsError || tokenResponse.IsHttpError)
        {
            throw new SecurityTokenException("Could not retrieve token.");
        }

        //set Token to the new token and set the expiry time to the new expiry time
        Token = tokenResponse;
        ExpiryTime = DateTime.UtcNow.AddSeconds(Token.ExpiresIn);

        //return fresh token
        return Token;
    }
}

In other words - you need to cache that token somehow. 换句话说 - 你需要以某种方式缓存该令牌。 When you request the token, you get an ExpiresIn in the response - this will tell you how long the token will be valid. 当您请求令牌时,您会在响应中获得ExpiresIn - 这将告诉您令牌有效期多长。

Another option is to wait until the API returns a 401 - and then request a new token. 另一种选择是等待API返回401 - 然后请求新令牌。

Refresh tokens are not used with client credentials flow. 刷新令牌不与客户端凭据流一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM