Search in sources :

Example 21 with JsonWebToken

use of org.keycloak.representations.JsonWebToken in project keycloak by keycloak.

the class JsonWebTokenTest method isActiveShouldReturnTrueWhenBeforeTimeInFutureWithinTimeSkew.

@Test
public void isActiveShouldReturnTrueWhenBeforeTimeInFutureWithinTimeSkew() {
    int notBeforeTime = Time.currentTime() + 5;
    int allowedClockSkew = 10;
    JsonWebToken jsonWebToken = new JsonWebToken();
    jsonWebToken.notBefore(notBeforeTime);
    assertTrue(jsonWebToken.isActive(allowedClockSkew));
}
Also used : JsonWebToken(org.keycloak.representations.JsonWebToken) Test(org.junit.Test)

Example 22 with JsonWebToken

use of org.keycloak.representations.JsonWebToken in project keycloak by keycloak.

the class JsonWebTokenTest method testAddAudience.

@Test
public void testAddAudience() {
    // Token with no audience
    JsonWebToken s = new JsonWebToken();
    s.addAudience("audience-1");
    assertArrayEquals(new String[] { "audience-1" }, s.getAudience());
    // Add to existing
    s.addAudience("audience-2");
    assertArrayEquals(new String[] { "audience-1", "audience-2" }, s.getAudience());
    s.addAudience("audience-3");
    assertArrayEquals(new String[] { "audience-1", "audience-2", "audience-3" }, s.getAudience());
    // Add existing. Shouldn't be added as it's already there
    s.addAudience("audience-2");
    assertArrayEquals(new String[] { "audience-1", "audience-2", "audience-3" }, s.getAudience());
}
Also used : JsonWebToken(org.keycloak.representations.JsonWebToken) Test(org.junit.Test)

Example 23 with JsonWebToken

use of org.keycloak.representations.JsonWebToken in project keycloak by keycloak.

the class AuthUtil method getSignedRequestToken.

public static String getSignedRequestToken(String keystore, String storePass, String keyPass, String alias, int sigLifetime, String clientId, String realmInfoUrl) {
    KeyPair keypair = KeystoreUtil.loadKeyPairFromKeystore(keystore, storePass, keyPass, alias, KeystoreUtil.KeystoreFormat.JKS);
    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(UUID.randomUUID().toString());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);
    int now = Time.currentTime();
    reqToken.issuedAt(now);
    reqToken.expiration(now + sigLifetime);
    reqToken.notBefore(now);
    String signedRequestToken = new JWSBuilder().jsonContent(reqToken).rsa256(keypair.getPrivate());
    return signedRequestToken;
}
Also used : KeyPair(java.security.KeyPair) JsonWebToken(org.keycloak.representations.JsonWebToken) JWSBuilder(org.keycloak.jose.jws.JWSBuilder)

Example 24 with JsonWebToken

use of org.keycloak.representations.JsonWebToken in project keycloak by keycloak.

the class OIDCIdentityProvider method getFederatedIdentity.

@Override
public BrokeredIdentityContext getFederatedIdentity(String response) {
    AccessTokenResponse tokenResponse = null;
    try {
        tokenResponse = JsonSerialization.readValue(response, AccessTokenResponse.class);
    } catch (IOException e) {
        throw new IdentityBrokerException("Could not decode access token response.", e);
    }
    String accessToken = verifyAccessToken(tokenResponse);
    String encodedIdToken = tokenResponse.getIdToken();
    JsonWebToken idToken = validateToken(encodedIdToken);
    try {
        BrokeredIdentityContext identity = extractIdentity(tokenResponse, accessToken, idToken);
        if (!identity.getId().equals(idToken.getSubject())) {
            throw new IdentityBrokerException("Mismatch between the subject in the id_token and the subject from the user_info endpoint");
        }
        identity.getContextData().put(BROKER_NONCE_PARAM, idToken.getOtherClaims().get(OIDCLoginProtocol.NONCE_PARAM));
        if (getConfig().isStoreToken()) {
            if (tokenResponse.getExpiresIn() > 0) {
                long accessTokenExpiration = Time.currentTime() + tokenResponse.getExpiresIn();
                tokenResponse.getOtherClaims().put(ACCESS_TOKEN_EXPIRATION, accessTokenExpiration);
                response = JsonSerialization.writeValueAsString(tokenResponse);
            }
            identity.setToken(response);
        }
        return identity;
    } catch (Exception e) {
        throw new IdentityBrokerException("Could not fetch attributes from userinfo endpoint.", e);
    }
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) JsonWebToken(org.keycloak.representations.JsonWebToken) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) OAuthErrorException(org.keycloak.OAuthErrorException) ErrorResponseException(org.keycloak.services.ErrorResponseException) JWSInputException(org.keycloak.jose.jws.JWSInputException) IOException(java.io.IOException) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException)

Example 25 with JsonWebToken

use of org.keycloak.representations.JsonWebToken in project keycloak by keycloak.

the class OIDCIdentityProvider method validateToken.

protected JsonWebToken validateToken(String encodedToken, boolean ignoreAudience) {
    if (encodedToken == null) {
        throw new IdentityBrokerException("No token from server.");
    }
    JsonWebToken token;
    try {
        JWSInput jws = new JWSInput(encodedToken);
        if (!verify(jws)) {
            throw new IdentityBrokerException("token signature validation failed");
        }
        token = jws.readJsonContent(JsonWebToken.class);
    } catch (JWSInputException e) {
        throw new IdentityBrokerException("Invalid token", e);
    }
    String iss = token.getIssuer();
    if (!token.isActive(getConfig().getAllowedClockSkew())) {
        throw new IdentityBrokerException("Token is no longer valid");
    }
    if (!ignoreAudience && !token.hasAudience(getConfig().getClientId())) {
        throw new IdentityBrokerException("Wrong audience from token.");
    }
    if (!ignoreAudience && (token.getIssuedFor() != null && !getConfig().getClientId().equals(token.getIssuedFor()))) {
        throw new IdentityBrokerException("Token issued for does not match client id");
    }
    String trustedIssuers = getConfig().getIssuer();
    if (trustedIssuers != null && trustedIssuers.length() > 0) {
        String[] issuers = trustedIssuers.split(",");
        for (String trustedIssuer : issuers) {
            if (iss != null && iss.equals(trustedIssuer.trim())) {
                return token;
            }
        }
        throw new IdentityBrokerException("Wrong issuer from token. Got: " + iss + " expected: " + getConfig().getIssuer());
    }
    return token;
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) JsonWebToken(org.keycloak.representations.JsonWebToken)

Aggregations

JsonWebToken (org.keycloak.representations.JsonWebToken)36 Test (org.junit.Test)12 JWSInput (org.keycloak.jose.jws.JWSInput)7 JWSBuilder (org.keycloak.jose.jws.JWSBuilder)5 KeyPair (java.security.KeyPair)4 IdentityBrokerException (org.keycloak.broker.provider.IdentityBrokerException)4 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)4 OAuthClient (org.keycloak.testsuite.util.OAuthClient)4 PublicKey (java.security.PublicKey)3 OAuthErrorException (org.keycloak.OAuthErrorException)3 JWSInputException (org.keycloak.jose.jws.JWSInputException)3 IOException (java.io.IOException)2 PrivateKey (java.security.PrivateKey)2 LinkedList (java.util.LinkedList)2 Response (javax.ws.rs.core.Response)2 NameValuePair (org.apache.http.NameValuePair)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)2 ClientResource (org.keycloak.admin.client.resource.ClientResource)2 BrokeredIdentityContext (org.keycloak.broker.provider.BrokeredIdentityContext)2