Search in sources :

Example 6 with JsonWebToken

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

the class ClientRegistrationTokenUtils method verifyToken.

public static TokenVerification verifyToken(KeycloakSession session, RealmModel realm, String token) {
    if (token == null) {
        return TokenVerification.error(new RuntimeException("Missing token"));
    }
    String kid;
    JsonWebToken jwt;
    try {
        TokenVerifier<JsonWebToken> verifier = TokenVerifier.create(token, JsonWebToken.class).withChecks(new TokenVerifier.RealmUrlCheck(getIssuer(session, realm)), TokenVerifier.IS_ACTIVE);
        SignatureVerifierContext verifierContext = session.getProvider(SignatureProvider.class, verifier.getHeader().getAlgorithm().name()).verifier(verifier.getHeader().getKeyId());
        verifier.verifierContext(verifierContext);
        kid = verifierContext.getKid();
        verifier.verify();
        jwt = verifier.getToken();
    } catch (VerificationException e) {
        return TokenVerification.error(new RuntimeException("Failed decode token", e));
    }
    if (!(TokenUtil.TOKEN_TYPE_BEARER.equals(jwt.getType()) || TYPE_INITIAL_ACCESS_TOKEN.equals(jwt.getType()) || TYPE_REGISTRATION_ACCESS_TOKEN.equals(jwt.getType()))) {
        return TokenVerification.error(new RuntimeException("Invalid type of token"));
    }
    return TokenVerification.success(kid, jwt);
}
Also used : SignatureProvider(org.keycloak.crypto.SignatureProvider) SignatureVerifierContext(org.keycloak.crypto.SignatureVerifierContext) TokenVerifier(org.keycloak.TokenVerifier) VerificationException(org.keycloak.common.VerificationException) JsonWebToken(org.keycloak.representations.JsonWebToken)

Example 7 with JsonWebToken

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

the class DefaultTokenExchangeProvider method tokenExchange.

protected Response tokenExchange() {
    UserModel tokenUser = null;
    UserSessionModel tokenSession = null;
    AccessToken token = null;
    String subjectToken = formParams.getFirst(OAuth2Constants.SUBJECT_TOKEN);
    if (subjectToken != null) {
        String subjectTokenType = formParams.getFirst(OAuth2Constants.SUBJECT_TOKEN_TYPE);
        String realmIssuerUrl = Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName());
        String subjectIssuer = formParams.getFirst(OAuth2Constants.SUBJECT_ISSUER);
        if (subjectIssuer == null && OAuth2Constants.JWT_TOKEN_TYPE.equals(subjectTokenType)) {
            try {
                JWSInput jws = new JWSInput(subjectToken);
                JsonWebToken jwt = jws.readJsonContent(JsonWebToken.class);
                subjectIssuer = jwt.getIssuer();
            } catch (JWSInputException e) {
                event.detail(Details.REASON, "unable to parse jwt subject_token");
                event.error(Errors.INVALID_TOKEN);
                throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_TOKEN, "Invalid token type, must be access token", Response.Status.BAD_REQUEST);
            }
        }
        if (subjectIssuer != null && !realmIssuerUrl.equals(subjectIssuer)) {
            event.detail(OAuth2Constants.SUBJECT_ISSUER, subjectIssuer);
            return exchangeExternalToken(subjectIssuer, subjectToken);
        }
        if (subjectTokenType != null && !subjectTokenType.equals(OAuth2Constants.ACCESS_TOKEN_TYPE)) {
            event.detail(Details.REASON, "subject_token supports access tokens only");
            event.error(Errors.INVALID_TOKEN);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_TOKEN, "Invalid token type, must be access token", Response.Status.BAD_REQUEST);
        }
        AuthenticationManager.AuthResult authResult = AuthenticationManager.verifyIdentityToken(session, realm, session.getContext().getUri(), clientConnection, true, true, null, false, subjectToken, headers);
        if (authResult == null) {
            event.detail(Details.REASON, "subject_token validation failure");
            event.error(Errors.INVALID_TOKEN);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.BAD_REQUEST);
        }
        tokenUser = authResult.getUser();
        tokenSession = authResult.getSession();
        token = authResult.getToken();
    }
    String requestedSubject = formParams.getFirst(OAuth2Constants.REQUESTED_SUBJECT);
    if (requestedSubject != null) {
        event.detail(Details.REQUESTED_SUBJECT, requestedSubject);
        UserModel requestedUser = session.users().getUserByUsername(realm, requestedSubject);
        if (requestedUser == null) {
            requestedUser = session.users().getUserById(realm, requestedSubject);
        }
        if (requestedUser == null) {
            // We always returned access denied to avoid username fishing
            event.detail(Details.REASON, "requested_subject not found");
            event.error(Errors.NOT_ALLOWED);
            throw new CorsErrorResponseException(cors, OAuthErrorException.ACCESS_DENIED, "Client not allowed to exchange", Response.Status.FORBIDDEN);
        }
        if (token != null) {
            event.detail(Details.IMPERSONATOR, tokenUser.getUsername());
            // for this case, the user represented by the token, must have permission to impersonate.
            AdminAuth auth = new AdminAuth(realm, token, tokenUser, client);
            if (!AdminPermissions.evaluator(session, realm, auth).users().canImpersonate(requestedUser)) {
                event.detail(Details.REASON, "subject not allowed to impersonate");
                event.error(Errors.NOT_ALLOWED);
                throw new CorsErrorResponseException(cors, OAuthErrorException.ACCESS_DENIED, "Client not allowed to exchange", Response.Status.FORBIDDEN);
            }
        } else {
            // to impersonate
            if (client.isPublicClient()) {
                event.detail(Details.REASON, "public clients not allowed");
                event.error(Errors.NOT_ALLOWED);
                throw new CorsErrorResponseException(cors, OAuthErrorException.ACCESS_DENIED, "Client not allowed to exchange", Response.Status.FORBIDDEN);
            }
            if (!AdminPermissions.management(session, realm).users().canClientImpersonate(client, requestedUser)) {
                event.detail(Details.REASON, "client not allowed to impersonate");
                event.error(Errors.NOT_ALLOWED);
                throw new CorsErrorResponseException(cors, OAuthErrorException.ACCESS_DENIED, "Client not allowed to exchange", Response.Status.FORBIDDEN);
            }
        }
        tokenSession = session.sessions().createUserSession(realm, requestedUser, requestedUser.getUsername(), clientConnection.getRemoteAddr(), "impersonate", false, null, null);
        if (tokenUser != null) {
            tokenSession.setNote(IMPERSONATOR_ID.toString(), tokenUser.getId());
            tokenSession.setNote(IMPERSONATOR_USERNAME.toString(), tokenUser.getUsername());
        }
        tokenUser = requestedUser;
    }
    String requestedIssuer = formParams.getFirst(OAuth2Constants.REQUESTED_ISSUER);
    if (requestedIssuer == null) {
        return exchangeClientToClient(tokenUser, tokenSession);
    } else {
        try {
            return exchangeToIdentityProvider(tokenUser, tokenSession, requestedIssuer);
        } finally {
            if (subjectToken == null) {
                // we are naked! So need to clean up user session
                try {
                    session.sessions().removeUserSession(realm, tokenSession);
                } catch (Exception ignore) {
                }
            }
        }
    }
}
Also used : UserModel(org.keycloak.models.UserModel) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AdminAuth(org.keycloak.services.resources.admin.AdminAuth) UserSessionModel(org.keycloak.models.UserSessionModel) AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) JsonWebToken(org.keycloak.representations.JsonWebToken) OAuthErrorException(org.keycloak.OAuthErrorException) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) JWSInputException(org.keycloak.jose.jws.JWSInputException)

Example 8 with JsonWebToken

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

the class AbstractClientPoliciesTest method createSignedRequestToken.

// Signed JWT for client authentication utility
protected String createSignedRequestToken(String clientId, PrivateKey privateKey, PublicKey publicKey, String algorithm) {
    JsonWebToken jwt = createRequestToken(clientId, getRealmInfoUrl());
    String kid = KeyUtils.createKeyId(publicKey);
    SignatureSignerContext signer = oauth.createSigner(privateKey, kid, algorithm);
    return new JWSBuilder().kid(kid).jsonContent(jwt).sign(signer);
}
Also used : SignatureSignerContext(org.keycloak.crypto.SignatureSignerContext) JsonWebToken(org.keycloak.representations.JsonWebToken) JWSBuilder(org.keycloak.jose.jws.JWSBuilder)

Example 9 with JsonWebToken

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

the class AbstractClientPoliciesTest method createRequestToken.

private 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.iat(Long.valueOf(now));
    reqToken.exp(Long.valueOf(now + 10));
    reqToken.nbf(Long.valueOf(now));
    return reqToken;
}
Also used : JsonWebToken(org.keycloak.representations.JsonWebToken)

Example 10 with JsonWebToken

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

the class ClientAuthSignedJWTTest method createRequestToken.

private 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 + 10);
    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