keycloak openIdConnect adapter token 验证

Token 认证,调用关系:


 

Token验证核心类 AdapterRSATokenVerifier 所在包

相关代码

public static AccessToken verifyToken(String tokenString, KeycloakDeployment deployment, boolean checkActive, boolean checkTokenType) throws VerificationException {

        RSATokenVerifier verifier = RSATokenVerifier

.create(tokenString)

.realmUrl(deployment.getRealmInfoUrl())

.checkActive(checkActive)

.checkTokenType(checkTokenType);

        PublicKey publicKey = getPublicKey(verifier.getHeader().getKeyId(), deployment);

        return verifier.publicKey(publicKey).verify().getToken();

}

 

 

 

 @Override

    public PublicKey getPublicKey(String kid, KeycloakDeployment deployment) {

        int minTimeBetweenRequests = deployment.getMinTimeBetweenJwksRequests();

        int publicKeyCacheTtl = deployment.getPublicKeyCacheTtl();

        int currentTime = Time.currentTime();

 

        // Check if key is in cache.

        PublicKey publicKey = lookupCachedKey(publicKeyCacheTtl, currentTime, kid);

        if (publicKey != null) {

            return publicKey;

        }

 

        // Check if we are allowed to send request

        synchronized (this) {

            currentTime = Time.currentTime();

            if (currentTime > lastRequestTime + minTimeBetweenRequests) {

                sendRequest(deployment);

                lastRequestTime = currentTime;

            } else {

                log.debug("Won't send request to realm jwks url. Last request time was " + lastRequestTime);

            }

 

            return lookupCachedKey(publicKeyCacheTtl, currentTime, kid);

        }

    }

 

 private void sendRequest(KeycloakDeployment deployment) {

        if (log.isTraceEnabled()) {

            log.trace("Going to send request to retrieve new set of realm public keys for client " + deployment.getResourceName());

        }

 

        HttpGet getMethod = new HttpGet(deployment.getJwksUrl());

        try {

            JSONWebKeySet jwks = HttpAdapterUtils.sendJsonHttpRequest(deployment, getMethod, JSONWebKeySet.class);

 

            Map<String, PublicKey> publicKeys = JWKSUtils.getKeysForUse(jwks, JWK.Use.SIG);

 

            if (log.isDebugEnabled()) {

                log.debug("Realm public keys successfully retrieved for client " +  deployment.getResourceName() + ". New kids: " + publicKeys.keySet().toString());

            }

 

            // Update current keys

            currentKeys.clear();

            currentKeys.putAll(publicKeys);

 

        } catch (HttpClientAdapterException e) {

            log.error("Error when sending request to retrieve realm keys", e);

        }

    }

 

=================================================================

 

说明:deployment.getJwksUrl()的值就是:

http://keycloak地址/auth/realms/{RealmName}/protocol/openid-connect/certs

 

 

 

 

 

 

 

 

 

 

 


 

猜你喜欢

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