Home > front end >  IdentityModel RequestRefreshTokenAsync method always return invalid_client
IdentityModel RequestRefreshTokenAsync method always return invalid_client

Time:02-28

I have the following code:

public async Task<TokenResponse> RefreshTokenAsync(string refreshToken)
{
    HttpClient client = new();
    var discoveryResponse = await client.GetDiscoveryDocumentAsync("https://localhost:44334");

    var response = await client.RequestRefreshTokenAsync(new RefreshTokenRequest
    {
        Address = discoveryResponse.TokenEndpoint,
        ClientId = "...",
        ClientSecret = "...",
        RefreshToken = refreshToken
    });

    return response;
}

And it always returns 400 Bad Request with invalid_client message. When I'm refreshing token in Postman it works well. Where is the problem?

CodePudding user response:

The purpose of the refresh-token is: the user does not need to re-authenticate with the credentials (username/password) in the application every time the session expires. So your application needs to connect to the endpoint identity and consume a new refresh token before the token or refresh token times out. In asp dotnet core Identity and JwtToken always have a default timeout value; whatever: you need to capture the refresh token before this timeout expires, otherwise your identity understands the user who does not have the browser open or is not online. This may imply developing a routine that stays in Roudin-Robin always refreshing the application with the new Token while the browser is open.

CodePudding user response:

I changed my code to this:

public async Task<TokenResponse> RefreshTokenAsync(string refreshToken)
{
    HttpClient client = new();
    var discoveryResponse = await client.GetDiscoveryDocumentAsync("https://localhost:44334");

    var tokenClient = new TokenClient(client, new TokenClientOptions
    {
        Address = discoveryResponse.TokenEndpoint,
        ClientId = "...",
        ClientSecret = "...",
    });

    var response = await tokenClient.RequestRefreshTokenAsync(refreshToken);
    response.HttpResponse.EnsureSuccessStatusCode();

    return response;
}

And now it works as expected.

  • Related