How can I test if my token is expired with IdentityServer4?

好久不见. 提交于 2020-01-25 09:49:24

问题


I create a token with IdentityServer4 I copy this example I just modify this

in IdentityServer -> Config

public static IEnumerable<Client> GetClients()

{
    return new List<Client>
    {
        new Client
        {
            ClientId = "client",
            AllowedGrantTypes = GrantTypes.ClientCredentials,
            ClientSecrets =
            {
                new Secret("secret".Sha256())
            },
            AllowedScopes = { "TRACEITLMAPI" },
            AccessTokenLifetime = 10,
            IdentityTokenLifetime = 10 

        }
    };
}

I wanted to test when my token will be expired.


回答1:


An access token is a self-contained package that contains three parts:

  • header
  • payload
  • signature

The information is in the payload, while the signature ensures the receiver that the payload has not been altered.

Taking the terminology from the documentation into account:

The resource has the information that needs to be protected. The client is the process that wants to access the resource and IdentityServer is the issuer of the access token that the client can use to access the resource.

The token is created by the IdentityServer and the client sends it along with the request in the header to the resource. So it's the resource that needs to validate the token. Being self-contained, means that the resource doesn't have to contact the issuer and can fully trust the token after validation. Luckily, middleware takes care of that, so you don't have to write code for that.

The token should be short-lived, so it's rather seconds, minutes perhaps hours than days. Being short-lived means that the client may want to read the token as well. Not necessarily to validate it, but at least to check whether it's not expired. Because it may have to request a new token.

Now to answer your question, the client can read the token and validate it as follows:

// using System.IdentityModel.Tokens.Jwt;

var tokenHandler = new JwtSecurityTokenHandler();
var jwtSecurityToken = tokenHandler.ReadJwtToken(tokenResponse.AccessToken);

if (jwtSecurityToken.ValidTo < DateTime.UtcNow.AddSeconds(10))
    Console.WriteLine("Expired");

Please note that this is local validation in the client. This doesn't mean the token isn't accepted by the resource.

The reason is that there's a configurable tolerance level of accepting the token (clock skew). I believe this is by default five minutes. So while the client may have determined that the token is expired, the resource may still accept it if it's within tolerable range.

But this is not something you can count on. So it's better to refresh the token or request a new token (depending on the flow) when the token is (almost) expired.

Some remarks, since the token can't be altered and there's no need for the resource to contact the issuer, there is no way to revoke the token. Therefor it's necessary to set an expiration time. Please note that a new token doesn't invalidate or revoke other (previous, older) tokens. A Jwt always remains valid until it expires.

And about the statement in your answer, this has nothing to do with the validity of the token. This simply prints a string value:

Console.WriteLine(tokenResponse.AccessToken);

Where tokenResponse is the result of the request (RequestClientCredentialsTokenAsync) and AccessToken is a property in the response object.




回答2:


Assuming that the token in question is a JWT then the expiry time is contained within the token itself as the exp claim in Unix epoch format. Check out https://jwt.io - it has a useful token visualisation tool on the front page.

If you want to test it against an API that has been configured to accept your access tokens then bear in mind that there's usually a significant (i.e. in the order of minutes) clock skew allowance so even if your token has expired according to an accurate clock the API will continue to accept it. This is by design and the level of clock skew allowed should be configurable.



来源:https://stackoverflow.com/questions/58997487/how-can-i-test-if-my-token-is-expired-with-identityserver4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!