keycloak AccessToken签名验证和有效性检查

Validating Access Tokens

If you need to manually validate access tokens issued by Keycloak you can invoke the Introspection Endpoint. The downside【负面、消极面】 to this approach【方法、途径】 is that you have to make a network invocation to the Keycloak server. This can be slow and possibily overload the server if you have too many validation requests going on at the same time. Keycloak issued access tokens are JSON Web Tokens (JWT) digitally signed and encoded using JSON Web Signature (JWS). Because they are encoded in this way, this allows you to locally validate access tokens using the public key of the issuing realm. You can either hard code the realm’s public key in your validation code, or lookup and cache the public key using the certificate endpoint with the Key ID (KID) embedded within the JWS. Depending what language you code in, there are a multitude of third party libraries out there that can help you with JWS validation.

keycloak AccessToken验证过程

1、解码 token(注意是解码,不是解密,因为token是不加密的,只是按照一定规则进行编码,并签名)。

2、取得配置的 publickey(含 kid),或根据配置的keycloak地址和realm信息,调用keycloak的Rest接口( /realms/{realm-name}/protocol/openid-connect/certs)查询publicKey(含kid)。

3、从步骤2中得到的publicKey中,查找与步骤1中得到的kid匹配的publicKey。

4、如果找不到对应的publicKey,则报异常:Didn't find publicKey for specified kid。

5、使用publicKey验证签名

6、检查Token中的subject属性是否为空,为空则报异常:Subject missing in token

7、检查配置realm url 与 token中的issuer是否匹配,不匹配则报异常:Invalid token issuer. Expected {realm url}, but was {issuer}

7、检查token是否已过期,已过期,则报异常:Token is not active

示例

package test;

import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.adapters.rotation.AdapterRSATokenVerifier;
import org.keycloak.common.VerificationException;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.adapters.config.AdapterConfig;

public class Test {

	public static void main(String[] args) throws VerificationException {
		
		//待验证 accessToken
		String tokenString = "************";
		
		//1、设置client配置信息
		AdapterConfig adapterConfig = new AdapterConfig();
		//realm name
		adapterConfig.setRealm("iottest");
		//client_id
		adapterConfig.setResource("iot_hub");
		//认证中心keycloak地址
		adapterConfig.setAuthServerUrl("http://keycloak/auth");
		
		//2、根据client配置信息构建KeycloakDeployment对象
		KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(adapterConfig);
		
		//3、执行token签名验证和有效性检查(不通过会抛异常)
		AccessToken accesToken = AdapterRSATokenVerifier.verifyToken(tokenString, deployment);
		System.out.println("验证通过");
			
	}

} 

解码后token内容



 

依赖包

依赖包下载,见附件。


 



猜你喜欢

转载自huangqiqing123.iteye.com/blog/2422879