如何使用IdentityServer4测试我的令牌是否已过期? [英] How can I test if my token is expired with IdentityServer4?

查看:905
本文介绍了如何使用IdentityServer4测试我的令牌是否已过期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用IdentityServer4创建令牌,然后将其复制示例我只是对此进行修改

IdentityServer 中-> 配置

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 

        }
    };
}

我想测试令牌何时过期.

解决方案

访问令牌是一个独立的软件包,其中包含术语:

资源具有需要保护的信息. client 是要访问资源的过程,而 IdentityServer 是访问令牌的发件人,客户端可以用来访问资源.

令牌是由IdentityServer创建的,客户端将其与标头中的请求一起发送到资源. 因此,这是需要验证令牌的资源.是自包含的,这意味着该资源不必与发行方联系,并且在验证后可以完全信任令牌 .幸运的是,中间件可以解决这个问题,因此您不必为此编写代码.

令牌应该是短命的,所以它应该是几秒钟,几分钟甚至几小时而不是几天.寿命短意味着 client 可能也希望读取令牌.不一定要验证它,但至少要检查它是否未过期.因为它可能必须请求新的令牌.

现在要回答您的问题,客户端可以读取令牌并按以下方式对其进行验证:

// 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");

请注意,这是客户端中的本地验证.这并不意味着该令牌未被资源接受.

原因是接受令牌存在可配置的容限级别(时钟偏斜).我相信这默认是五分钟.因此,尽管客户端可能已确定令牌已过期,但如果资源在可接受范围内,则资源仍可以接受令牌.

但这不是您可以指望的东西.因此,最好在令牌(几乎)过期时刷新令牌或请求新令牌(取决于流).

一些说明,由于令牌不能更改,并且不需要资源来与发行者联系,因此无法撤消令牌.因此,必须设置一个到期时间.请注意,新令牌不会使其他令牌失效或撤销. Jwt始终保持有效,直到过期.

关于答案中的陈述,这与令牌的有效性无关.这只是打印一个字符串值:

Console.WriteLine(tokenResponse.AccessToken);

tokenResponse是请求的结果(RequestClientCredentialsTokenAsync),AccessToken是响应对象中的属性.

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.

解决方案

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.

这篇关于如何使用IdentityServer4测试我的令牌是否已过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆