IdentityServer4 中配置 Client 的时候 Token 过期方式有两种,Token 的类型也有两种:
/// <summary> /// Access token types. /// </summary> public enum AccessTokenType { /// <summary> /// Self-contained Json Web Token /// </summary> Jwt = 0, /// <summary> /// Reference token /// </summary> Reference = 1 } /// <summary> /// Token expiration types. /// </summary> public enum TokenExpiration { /// <summary> /// Sliding token expiration /// </summary> Sliding = 0, /// <summary> /// Absolute token expiration /// </summary> Absolute = 1 }
IdentityServer4 使用非对称加密方式对 Token 进行签名与验证(验证 Token 的合法性,并且 RSA 必须 SHA256 算法),以确保验证 token 的合法性。开发环境一般使用 AddDeveloperSigningCredential 方法使用临时证书即可(先判断 tempkey.rsa 证书文件是否存在,如果不存在就创建一个新的 tempkey.rsa 证书),生成环境(负载集群)一般需要使用固定的证书文件。
在用到IdentityServer4生成签名token时,需要用到证书,查了一些资料后,下面就根据真实实践来重述 linux上生成 openssl 证书的过程。
本博的linux环境为CentOS7.4,openssl是默认安装的,没有的话可以用yum安装。
一、我们首先生成私匙,linux命令如下:
openssl genrsa -out server.key 2048
二、创建一个CSR(Certificate Signing Request)--证书签名的请求,linux命令如下:
openssl req -new -key server.key -out server.csr
此时,会有一些提示信息,让你输入国家,城市,组织,邮箱等等信息,你可以输入对应的信息,当然也可以不用输入,一直按回车即可。三、生成证书,linux命令如下:
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
-days 是证书有效期,可自己根据需要填写。四、现在证书和私匙都有了,然后我们需要给他们俩封装成一个文件, 以便Identity server可以使用它们去正确的签名tokens. 这就需要使用另一个linux命令:
openssl pkcs12 -export -in server.crt -inkey server.key -out server.pfx
此时会提示输入密码,然后再确认下密码,就完成了。最后把证书路径和密码放到IdentityServer的配置里即可。
Self-contained Json Web Token(默认使用 RFC 7519 - JSON Web Token (JWT))
API 端(资源服务器)收到第一个请求后(仅第一次请求,后续的请求都使用第一次获得的公钥进行验证),会去 IdentityServer 服务端调用 /.well-known/openid-configuration/jwks 接口获取 RSA 公钥验签以确认 token 是否合法。另外使用 JWT 的方式 token 是不可撤销的(POST /connect/revocation)。
Reference token
API 端(资源服务器)需要每次去访问 IdentityServer 的 token 验证接口(POST /connect/introspect),当然 API 端也可以配置一定的时间来缓存结果,以减少验证的频率。
.AddIdentityServerAuthentication(options => { // base-address of your identityserver options.Authority = "https://demo.identityserver.io"; // name of the API resource options.ApiName = "api1"; options.ApiSecret = "secret"; options.EnableCaching = true; options.CacheDuration = TimeSpan.FromMinutes(10); // that's the default })
备注:Access token validation middleware
Jwt token 与 Reference token 相应的中间件也不一样(Microsoft.AspNetCore.Authentication.JwtBearer,IdentityModel.AspNetCore.OAuth2Introspection ),为了方便官方把两者集成到了一起(IdentityServer4.AccessTokenValidation)。
REFER:
https://identityserver4.readthedocs.io/en/release/topics/reference_tokens.html
https://identityserver4.readthedocs.io/en/release/topics/crypto.html#refcrypto
https://blogs.msdn.microsoft.com/webdev/2016/10/27/bearer-token-authentication-in-asp-net-core/
https://www.cnblogs.com/edisonchou/p/identityserver4_foundation_and_quickstart_01.html
用 Identity Server 4 (JWKS 端点和 RS256 算法) 来保护 Python web api
https://www.cnblogs.com/cgzl/p/8270677.html