Search in sources :

Example 11 with HttpException

use of io.jans.ca.server.HttpException in project jans by JanssenProject.

the class GetJwksOperation method execute.

@Override
public IOpResponse execute(GetJwksParams params) {
    if (StringUtils.isEmpty(params.getOpHost()) && StringUtils.isEmpty(params.getOpConfigurationEndpoint())) {
        throw new HttpException(ErrorResponseCode.INVALID_OP_HOST_AND_CONFIGURATION_ENDPOINT);
    }
    try {
        final DiscoveryService discoveryService = getDiscoveryService();
        final OpenIdConfigurationResponse openIdConfigurationResponse = discoveryService.getConnectDiscoveryResponse(params.getOpConfigurationEndpoint(), params.getOpHost(), params.getOpDiscoveryPath());
        final String jwksUri = openIdConfigurationResponse.getJwksUri();
        final JwkClient jwkClient = new JwkClient(jwksUri);
        jwkClient.setExecutor(getHttpService().getClientEngine());
        final JwkResponse serverResponse = jwkClient.exec();
        final GetJwksResponse response = new GetJwksResponse();
        response.setKeys(serverResponse.getJwks().getKeys());
        return new POJOResponse(response);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : JwkResponse(io.jans.as.client.JwkResponse) POJOResponse(io.jans.ca.common.response.POJOResponse) GetJwksResponse(io.jans.ca.common.response.GetJwksResponse) HttpException(io.jans.ca.server.HttpException) OpenIdConfigurationResponse(io.jans.as.client.OpenIdConfigurationResponse) DiscoveryService(io.jans.ca.server.service.DiscoveryService) HttpException(io.jans.ca.server.HttpException) JwkClient(io.jans.as.client.JwkClient)

Example 12 with HttpException

use of io.jans.ca.server.HttpException in project jans by JanssenProject.

the class GetTokensByCodeOperation method execute.

@Override
public IOpResponse execute(GetTokensByCodeParams params) throws Exception {
    validate(params);
    final Rp rp = getRp();
    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(rp);
    final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(params.getCode());
    tokenRequest.setRedirectUri(rp.getRedirectUri());
    tokenRequest.setAuthUsername(rp.getClientId());
    AuthenticationMethod authenticationMethod = Strings.isNullOrEmpty(params.getAuthenticationMethod()) ? AuthenticationMethod.fromString(rp.getTokenEndpointAuthMethod()) : AuthenticationMethod.fromString(params.getAuthenticationMethod());
    if (authenticationMethod == null) {
        LOG.debug("TokenEndpointAuthMethod is either not set or not valid. Setting `client_secret_basic` as AuthenticationMethod. TokenEndpointAuthMethod : {} ", rp.getTokenEndpointAuthMethod());
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    } else {
        tokenRequest.setAuthenticationMethod(authenticationMethod);
    }
    if (Lists.newArrayList(AuthenticationMethod.PRIVATE_KEY_JWT, AuthenticationMethod.TLS_CLIENT_AUTH, AuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH).contains(authenticationMethod)) {
        Algorithm algorithm = Strings.isNullOrEmpty(params.getAlgorithm()) ? Algorithm.fromString(rp.getTokenEndpointAuthSigningAlg()) : Algorithm.fromString(params.getAlgorithm());
        if (algorithm == null) {
            LOG.error("TokenEndpointAuthSigningAlg is either not set or not valid. TokenEndpointAuthSigningAlg : {} ", rp.getTokenEndpointAuthSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        tokenRequest.setAlgorithm(SignatureAlgorithm.fromString(rp.getTokenEndpointAuthSigningAlg()));
        if (!getConfigurationService().getConfiguration().getEnableJwksGeneration()) {
            LOG.error("The Token Authentication Method is {}. Please set `enable_jwks_generation` (to `true`), `crypt_provider_key_store_path` and `crypt_provider_key_store_password` in `client-api-server.yml` to enable RP-jwks generation in jans-client-api.", authenticationMethod.toString());
            throw new HttpException(ErrorResponseCode.JWKS_GENERATION_DISABLE);
        }
        tokenRequest.setCryptoProvider(getKeyGeneratorService().getCryptoProvider());
        tokenRequest.setKeyId(getKeyGeneratorService().getCryptoProvider().getKeyId(getKeyGeneratorService().getKeys(), algorithm, Use.SIGNATURE));
        tokenRequest.setAudience(discoveryResponse.getTokenEndpoint());
    } else {
        tokenRequest.setAuthPassword(rp.getClientSecret());
    }
    final TokenClient tokenClient = getOpClientFactory().createTokenClient(discoveryResponse.getTokenEndpoint());
    tokenClient.setExecutor(getHttpService().getClientEngine());
    tokenClient.setRequest(tokenRequest);
    final TokenResponse response = tokenClient.exec();
    if (response.getStatus() == 200 || response.getStatus() == 302) {
        if (Strings.isNullOrEmpty(response.getIdToken())) {
            LOG.error("id_token is not returned. Please check: 1) OP log file for error (oxauth.log) 2) whether 'openid' scope is present for 'get_authorization_url' command");
            LOG.error("Entity: " + response.getEntity());
            throw new HttpException(ErrorResponseCode.NO_ID_TOKEN_RETURNED);
        }
        if (Strings.isNullOrEmpty(response.getAccessToken())) {
            LOG.error("access_token is not returned");
            throw new HttpException(ErrorResponseCode.NO_ACCESS_TOKEN_RETURNED);
        }
        final Jwt idToken = Jwt.parse(response.getIdToken());
        final Validator validator = new Validator.Builder().discoveryResponse(discoveryResponse).idToken(idToken).keyService(getKeyService()).opClientFactory(getOpClientFactory()).rpServerConfiguration(getConfigurationService().getConfiguration()).rp(rp).build();
        String state = getStateService().encodeExpiredObject(params.getState(), ExpiredObjectType.STATE);
        validator.validateNonce(getStateService());
        validator.validateIdToken();
        validator.validateAccessToken(response.getAccessToken());
        validator.validateState(state);
        // persist tokens
        rp.setIdToken(response.getIdToken());
        rp.setAccessToken(response.getAccessToken());
        getRpService().update(rp);
        getStateService().deleteExpiredObjectsByKey(state);
        LOG.trace("Scope: " + response.getScope());
        final GetTokensByCodeResponse opResponse = new GetTokensByCodeResponse();
        opResponse.setAccessToken(response.getAccessToken());
        opResponse.setIdToken(response.getIdToken());
        opResponse.setRefreshToken(response.getRefreshToken());
        opResponse.setExpiresIn(response.getExpiresIn() != null ? response.getExpiresIn() : -1);
        opResponse.setIdTokenClaims(Jackson2.createJsonMapper().readTree(idToken.getClaims().toJsonString()));
        return opResponse;
    } else {
        if (response.getStatus() == 400) {
            throw new HttpException(ErrorResponseCode.BAD_REQUEST_INVALID_CODE);
        }
        LOG.error("Failed to get tokens because response code is: " + response.getScope());
    }
    return null;
}
Also used : Jwt(io.jans.as.model.jwt.Jwt) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) TokenResponse(io.jans.as.client.TokenResponse) TokenRequest(io.jans.as.client.TokenRequest) OpenIdConfigurationResponse(io.jans.as.client.OpenIdConfigurationResponse) HttpException(io.jans.ca.server.HttpException) GetTokensByCodeResponse(io.jans.ca.common.response.GetTokensByCodeResponse) TokenClient(io.jans.as.client.TokenClient) Rp(io.jans.ca.server.service.Rp)

Example 13 with HttpException

use of io.jans.ca.server.HttpException in project jans by JanssenProject.

the class GetClientTokenOperation method execute.

@Override
public IOpResponse execute(GetClientTokenParams params) {
    try {
        final AuthenticationMethod authenticationMethod = AuthenticationMethod.fromString(params.getAuthenticationMethod());
        final String tokenEndpoint = getDiscoveryService().getConnectDiscoveryResponse(params.getOpConfigurationEndpoint(), params.getOpHost(), params.getOpDiscoveryPath()).getTokenEndpoint();
        final TokenClient tokenClient = getOpClientFactory().createTokenClient(tokenEndpoint);
        tokenClient.setExecutor(getHttpService().getClientEngine());
        final TokenResponse tokenResponse;
        if (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT) {
            LOG.trace("Getting client token with private_key_jwt client authentication ...");
            SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(params.getAlgorithm());
            if (algorithm == null) {
                throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
            }
            TokenRequest tokenRequest = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
            tokenRequest.setScope(scopeAsString(params));
            tokenRequest.setAuthUsername(params.getClientId());
            tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
            tokenRequest.setAlgorithm(algorithm);
            tokenRequest.setCryptoProvider(getCryptoProvider());
            tokenRequest.setKeyId(params.getKeyId());
            tokenRequest.setAudience(tokenEndpoint);
            tokenClient.setRequest(tokenRequest);
            tokenResponse = tokenClient.exec();
        } else {
            tokenResponse = tokenClient.execClientCredentialsGrant(scopeAsString(params), params.getClientId(), params.getClientSecret());
        }
        if (tokenResponse != null) {
            if (Util.allNotBlank(tokenResponse.getAccessToken())) {
                GetClientTokenResponse response = new GetClientTokenResponse();
                response.setAccessToken(tokenResponse.getAccessToken());
                response.setExpiresIn(tokenResponse.getExpiresIn());
                response.setRefreshToken(tokenResponse.getRefreshToken());
                response.setScope(Utils.stringToList(tokenResponse.getScope()));
                return response;
            } else {
                LOG.error("access_token is blank in response, params: " + params + ", response: " + tokenResponse);
                LOG.error("Please check AS logs for more details (oxauth.log for CE).");
            }
        } else {
            LOG.error("No response from TokenClient");
            LOG.error("Please check AS logs for more details (oxauth.log for CE).");
        }
    } catch (HttpException e) {
        throw e;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    throw HttpException.internalError();
}
Also used : GetClientTokenResponse(io.jans.ca.common.response.GetClientTokenResponse) TokenResponse(io.jans.as.client.TokenResponse) TokenRequest(io.jans.as.client.TokenRequest) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) HttpException(io.jans.ca.server.HttpException) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) GetClientTokenResponse(io.jans.ca.common.response.GetClientTokenResponse) TokenClient(io.jans.as.client.TokenClient) HttpException(io.jans.ca.server.HttpException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 14 with HttpException

use of io.jans.ca.server.HttpException in project jans by JanssenProject.

the class KeyGeneratorService method getKeys.

public JSONWebKeySet getKeys() {
    if (configuration.getEnableJwksGeneration()) {
        if (keys != null && !keys.getKeys().isEmpty()) {
            return this.keys;
        }
        // if keys not found then search in storage
        JSONWebKeySet keys = getKeysFromStorage();
        if (keys != null && !keys.getKeys().isEmpty()) {
            this.keys = keys;
            return this.keys;
        }
        // generate new keys in case they do not exist
        generateKeys();
        return this.keys;
    }
    LOG.info("Relying party JWKS generation is disabled in running jans_client_api instance. To enable it set `enable_jwks_generation` field to true in `client-api-server.yml`.");
    throw new HttpException(ErrorResponseCode.JWKS_GENERATION_DISABLE);
}
Also used : JSONWebKeySet(io.jans.as.model.jwk.JSONWebKeySet) HttpException(io.jans.ca.server.HttpException)

Example 15 with HttpException

use of io.jans.ca.server.HttpException in project jans by JanssenProject.

the class UmaTokenService method obtainTokenWithUserCredentials.

private Token obtainTokenWithUserCredentials(OpenIdConfigurationResponse discovery, Rp rp, UmaScopeType scopeType) {
    // 1. Request authorization and receive the authorization code.
    final List<ResponseType> responseTypes = Lists.newArrayList();
    responseTypes.add(ResponseType.CODE);
    responseTypes.add(ResponseType.ID_TOKEN);
    final String state = stateService.generateState();
    final AuthorizationRequest request = new AuthorizationRequest(responseTypes, rp.getClientId(), scopes(scopeType), rp.getRedirectUri(), null);
    request.setState(state);
    request.setAuthUsername(rp.getUserId());
    request.setAuthPassword(rp.getUserSecret());
    request.getPrompts().add(Prompt.NONE);
    final AuthorizeClient authorizeClient = new AuthorizeClient(discovery.getAuthorizationEndpoint());
    authorizeClient.setExecutor(httpService.getClientEngine());
    authorizeClient.setRequest(request);
    final AuthorizationResponse response1 = authorizeClient.exec();
    final String scope = response1.getScope();
    final String authorizationCode = response1.getCode();
    if (!state.equals(response1.getState())) {
        throw new HttpException(ErrorResponseCode.INVALID_STATE);
    }
    if (Util.allNotBlank(authorizationCode)) {
        // 2. Request access token using the authorization code.
        final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
        tokenRequest.setCode(authorizationCode);
        tokenRequest.setRedirectUri(rp.getRedirectUri());
        tokenRequest.setAuthUsername(rp.getClientId());
        tokenRequest.setAuthPassword(rp.getClientSecret());
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
        tokenRequest.setScope(scope);
        final TokenClient tokenClient1 = new TokenClient(discovery.getTokenEndpoint());
        tokenClient1.setRequest(tokenRequest);
        tokenClient1.setExecutor(httpService.getClientEngine());
        final TokenResponse response2 = tokenClient1.exec();
        if (response2.getStatus() == 200 && Util.allNotBlank(response2.getAccessToken())) {
            final Token token = TokenFactory.newToken(scopeType);
            token.setToken(response2.getAccessToken());
            token.setRefreshToken(response2.getRefreshToken());
            token.setExpiresIn(response2.getExpiresIn());
            return token;
        } else {
            LOG.error("Status: " + response2.getStatus() + ", Entity: " + response2.getEntity());
        }
    } else {
        LOG.debug("Authorization code is blank.");
    }
    throw new RuntimeException("Failed to obtain Token, scopeType: " + scopeType + ", site: " + rp);
}
Also used : UmaTokenResponse(io.jans.as.model.uma.UmaTokenResponse) HttpException(io.jans.ca.server.HttpException) Token(io.jans.ca.server.model.Token) ResponseType(io.jans.as.model.common.ResponseType)

Aggregations

HttpException (io.jans.ca.server.HttpException)34 Jwt (io.jans.as.model.jwt.Jwt)10 Rp (io.jans.ca.server.service.Rp)9 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)8 OpenIdConfigurationResponse (io.jans.as.client.OpenIdConfigurationResponse)6 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)6 Test (org.testng.annotations.Test)6 RegisterResponse (io.jans.as.client.RegisterResponse)5 RegisterClient (io.jans.as.client.RegisterClient)4 RegisterRequest (io.jans.as.client.RegisterRequest)4 AuthenticationMethod (io.jans.as.model.common.AuthenticationMethod)4 UmaMetadata (io.jans.as.model.uma.UmaMetadata)4 IOException (java.io.IOException)4 TokenClient (io.jans.as.client.TokenClient)3 TokenResponse (io.jans.as.client.TokenResponse)3 GrantType (io.jans.as.model.common.GrantType)3 SubjectType (io.jans.as.model.common.SubjectType)3 BlockEncryptionAlgorithm (io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)3 KeyEncryptionAlgorithm (io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm)3 Strings (com.google.common.base.Strings)2