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

hen*_*gst 9 c# identityserver4

我有一个允许匿名用户的ASP.NET核心MVC应用程序.此应用程序调用受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",
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的MVC应用程序中,我正在使用TokenClient一个令牌,我可以在向受保护的API发出请求时使用这样的令牌:

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");
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我在每次请求时都要求Identity Server提供新令牌,这可能不是一个好主意.

处理令牌的最佳做法是什么?如何在客户端(MVC应用程序)上保留它们以及如何处理刷新令牌以确保客户端在必要时获取新令牌?

Lut*_*ndo 11

您需要将该客户端包装在某种托管服务中(作为单例),以便您可以在任何需要的地方使用它.我们有一个令牌组件,用于遵循此流程的服务器到服务器通信:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)