Search in sources :

Example 11 with JsonWebToken

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

the class OIDCIdentityProvider method validateJwt.

protected final BrokeredIdentityContext validateJwt(EventBuilder event, String subjectToken, String subjectTokenType) {
    if (!getConfig().isValidateSignature()) {
        return validateExternalTokenThroughUserInfo(event, subjectToken, subjectTokenType);
    }
    event.detail("validation_method", "signature");
    if (getConfig().isUseJwksUrl()) {
        if (getConfig().getJwksUrl() == null) {
            event.detail(Details.REASON, "jwks url unset");
            event.error(Errors.INVALID_CONFIG);
            throw new ErrorResponseException(Errors.INVALID_CONFIG, "Invalid server config", Response.Status.BAD_REQUEST);
        }
    } else if (getConfig().getPublicKeySignatureVerifier() == null) {
        event.detail(Details.REASON, "public key unset");
        event.error(Errors.INVALID_CONFIG);
        throw new ErrorResponseException(Errors.INVALID_CONFIG, "Invalid server config", Response.Status.BAD_REQUEST);
    }
    JsonWebToken parsedToken = null;
    try {
        parsedToken = validateToken(subjectToken, true);
    } catch (IdentityBrokerException e) {
        logger.debug("Unable to validate token for exchange", e);
        event.detail(Details.REASON, "token validation failure");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    try {
        boolean idTokenType = OAuth2Constants.ID_TOKEN_TYPE.equals(subjectTokenType);
        BrokeredIdentityContext context = extractIdentity(null, idTokenType ? null : subjectToken, parsedToken);
        if (context == null) {
            event.detail(Details.REASON, "Failed to extract identity from token");
            event.error(Errors.INVALID_TOKEN);
            throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
        }
        if (idTokenType) {
            context.getContextData().put(VALIDATED_ID_TOKEN, subjectToken);
        } else {
            context.getContextData().put(KeycloakOIDCIdentityProvider.VALIDATED_ACCESS_TOKEN, parsedToken);
        }
        context.getContextData().put(EXCHANGE_PROVIDER, getConfig().getAlias());
        context.setIdp(this);
        context.setIdpConfig(getConfig());
        return context;
    } catch (IOException e) {
        logger.debug("Unable to extract identity from identity token", e);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) ErrorResponseException(org.keycloak.services.ErrorResponseException) IOException(java.io.IOException) JsonWebToken(org.keycloak.representations.JsonWebToken) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext)

Example 12 with JsonWebToken

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

the class AuthorizationAPITest method testResourceServerAsAudience.

public void testResourceServerAsAudience(String clientId, String resourceServerClientId, String authzConfigFile) throws Exception {
    AuthzClient authzClient = getAuthzClient(authzConfigFile);
    PermissionRequest request = new PermissionRequest();
    request.setResourceId("Resource A");
    String accessToken = new OAuthClient().realm("authz-test").clientId(clientId).doGrantAccessTokenRequest("secret", "marta", "password").getAccessToken();
    String ticket = authzClient.protection().permission().create(request).getTicket();
    // Ticket is opaque to client or resourceServer. The audience should be just an authorization server itself
    JsonWebToken ticketDecoded = JsonSerialization.readValue(new JWSInput(ticket).getContent(), JsonWebToken.class);
    Assert.assertFalse(ticketDecoded.hasAudience(clientId));
    Assert.assertFalse(ticketDecoded.hasAudience(resourceServerClientId));
    AuthorizationResponse response = authzClient.authorization(accessToken).authorize(new AuthorizationRequest(ticket));
    assertNotNull(response.getToken());
    AccessToken rpt = toAccessToken(response.getToken());
    assertEquals(resourceServerClientId, rpt.getAudience()[0]);
}
Also used : PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) AuthzClient(org.keycloak.authorization.client.AuthzClient) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) JWSInput(org.keycloak.jose.jws.JWSInput) JsonWebToken(org.keycloak.representations.JsonWebToken) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse)

Example 13 with JsonWebToken

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

the class DefaultHostnameTest method assertInitialAccessTokenFromMasterRealm.

private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException {
    ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation();
    rep.setCount(1);
    rep.setExpiration(10000);
    ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep);
    JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/realms/" + realm, token.getIssuer());
    ClientRegistration clientReg = ClientRegistration.create().url(AUTH_SERVER_ROOT, realm).build();
    clientReg.auth(Auth.token(initialAccess.getToken()));
    ClientRepresentation client = new ClientRepresentation();
    client.setEnabled(true);
    ClientRepresentation response = clientReg.create(client);
    String registrationAccessToken = response.getRegistrationAccessToken();
    JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/realms/" + realm, registrationToken.getIssuer());
}
Also used : ClientRegistration(org.keycloak.client.registration.ClientRegistration) ClientInitialAccessCreatePresentation(org.keycloak.representations.idm.ClientInitialAccessCreatePresentation) JWSInput(org.keycloak.jose.jws.JWSInput) ClientInitialAccessPresentation(org.keycloak.representations.idm.ClientInitialAccessPresentation) JsonWebToken(org.keycloak.representations.JsonWebToken) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation)

Example 14 with JsonWebToken

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

the class FixedHostnameTest method assertInitialAccessTokenFromMasterRealm.

private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException {
    ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation();
    rep.setCount(1);
    rep.setExpiration(10000);
    ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep);
    JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, token.getIssuer());
    ClientRegistration clientReg = ClientRegistration.create().url(authServerUrl, realm).build();
    clientReg.auth(Auth.token(initialAccess.getToken()));
    ClientRepresentation client = new ClientRepresentation();
    client.setEnabled(true);
    ClientRepresentation response = clientReg.create(client);
    String registrationAccessToken = response.getRegistrationAccessToken();
    JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, registrationToken.getIssuer());
}
Also used : ClientRegistration(org.keycloak.client.registration.ClientRegistration) ClientInitialAccessCreatePresentation(org.keycloak.representations.idm.ClientInitialAccessCreatePresentation) JWSInput(org.keycloak.jose.jws.JWSInput) ClientInitialAccessPresentation(org.keycloak.representations.idm.ClientInitialAccessPresentation) JsonWebToken(org.keycloak.representations.JsonWebToken) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation)

Example 15 with JsonWebToken

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

the class JWTClientCredentialsProvider method createRequestToken.

protected JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(AdapterUtils.generateId());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);
    int now = Time.currentTime();
    reqToken.issuedAt(now);
    reqToken.expiration(now + this.tokenTimeout);
    reqToken.notBefore(now);
    return reqToken;
}
Also used : 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