Search in sources :

Example 6 with Rp

use of io.jans.ca.server.service.Rp in project jans by JanssenProject.

the class SqlPersistenceServiceImpl method getRp.

public Rp getRp(String rpId) {
    Connection conn = null;
    try {
        conn = provider.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement query = conn.prepareStatement("select id, data from rp where id = ?");
        query.setString(1, rpId);
        ResultSet rs = query.executeQuery();
        rs.next();
        String data = rs.getString("data");
        query.close();
        conn.commit();
        Rp rp = MigrationService.parseRp(data);
        if (rp != null) {
            LOG.debug("Found RP id: " + rpId + ", RP : " + rp);
            return rp;
        } else {
            LOG.error("Failed to fetch RP by id: " + rpId);
            return null;
        }
    } catch (Exception e) {
        LOG.error("Failed to find RP by id: " + rpId + ". Error: " + e.getMessage(), e);
        rollbackSilently(conn);
        return null;
    } finally {
        IOUtils.closeSilently(conn);
    }
}
Also used : Rp(io.jans.ca.server.service.Rp)

Example 7 with Rp

use of io.jans.ca.server.service.Rp in project jans by JanssenProject.

the class UpdateSiteOperation method createRegisterClientRequest.

private RegisterRequest createRegisterClientRequest(Rp rp, UpdateSiteParams params) {
    final RegisterRequest request = RegisterRequestMapper.createRegisterRequest(rp);
    // force update
    request.setHttpMethod(HttpMethod.PUT);
    if (params.getResponseTypes() != null && !params.getResponseTypes().isEmpty()) {
        request.setResponseTypesStrings(params.getResponseTypes());
    }
    if (params.getRptAsJwt() != null) {
        request.setRptAsJwt(params.getRptAsJwt());
    }
    if (params.getGrantType() != null && !params.getGrantType().isEmpty()) {
        request.setGrantTypes(params.getGrantType().stream().map(item -> GrantType.fromString(item)).collect(Collectors.toList()));
    }
    Set<String> redirectUris = Sets.newLinkedHashSet();
    if (params.getRedirectUris() != null && !params.getRedirectUris().isEmpty()) {
        if (!params.getRedirectUris().stream().allMatch(uri -> Utils.isValidUrl(uri))) {
            throw new HttpException(ErrorResponseCode.INVALID_REDIRECT_URI);
        }
        redirectUris.addAll(params.getRedirectUris());
        List<String> redirectUriList = Lists.newArrayList(redirectUris);
        request.setRedirectUris(redirectUriList);
    }
    if (params.getAcrValues() != null && !params.getAcrValues().isEmpty()) {
        request.setDefaultAcrValues(params.getAcrValues());
    }
    if (params.getClaimsRedirectUri() != null && !params.getClaimsRedirectUri().isEmpty()) {
        request.setClaimsRedirectUris(params.getClaimsRedirectUri());
    }
    if (params.getAccessTokenAsJwt() != null) {
        request.setAccessTokenAsJwt(params.getAccessTokenAsJwt());
    }
    if (params.getAccessTokenSigningAlg() != null) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getAccessTokenSigningAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `access_token_signing_alg` property. Value: " + params.getAccessTokenSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        request.setAccessTokenSigningAlg(signatureAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getClientJwksUri())) {
        request.setJwksUri(params.getClientJwksUri());
    }
    if (params.getPostLogoutRedirectUris() != null && !params.getPostLogoutRedirectUris().isEmpty()) {
        request.setPostLogoutRedirectUris(Lists.newArrayList(params.getPostLogoutRedirectUris()));
    }
    if (params.getContacts() != null) {
        request.setContacts(params.getContacts());
    }
    if (params.getScope() != null) {
        request.setScope(params.getScope());
    }
    if (!Strings.isNullOrEmpty(params.getClientSectorIdentifierUri())) {
        request.setSectorIdentifierUri(params.getClientSectorIdentifierUri());
    }
    if (!Strings.isNullOrEmpty(params.getClientFrontchannelLogoutUri())) {
        request.setFrontChannelLogoutUri(params.getClientFrontchannelLogoutUri());
    }
    if (params.getClientRequestUris() != null && !params.getClientRequestUris().isEmpty()) {
        request.setRequestUris(params.getClientRequestUris());
    }
    if (params.getClientTokenEndpointAuthSigningAlg() != null) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getClientTokenEndpointAuthSigningAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `client_token_endpoint_auth_signing_alg` property. Value: " + params.getClientTokenEndpointAuthSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        request.setTokenEndpointAuthSigningAlg(SignatureAlgorithm.fromString(params.getClientTokenEndpointAuthSigningAlg()));
    }
    if (!Strings.isNullOrEmpty(params.getClientName())) {
        request.setClientName(params.getClientName());
    }
    if (!Strings.isNullOrEmpty(params.getLogoUri())) {
        request.setLogoUri(params.getLogoUri());
    }
    if (!Strings.isNullOrEmpty(params.getClientUri())) {
        request.setClientUri(params.getClientUri());
    }
    if (!Strings.isNullOrEmpty(params.getPolicyUri())) {
        request.setPolicyUri(params.getPolicyUri());
    }
    if (params.getFrontChannelLogoutSessionRequired() != null) {
        request.setFrontChannelLogoutSessionRequired(params.getFrontChannelLogoutSessionRequired());
    }
    if (!Strings.isNullOrEmpty(params.getTosUri())) {
        request.setTosUri(params.getTosUri());
    }
    if (!Strings.isNullOrEmpty(params.getJwks())) {
        request.setJwks(params.getJwks());
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenBindingCnf())) {
        request.setIdTokenTokenBindingCnf(params.getIdTokenBindingCnf());
    }
    if (!Strings.isNullOrEmpty(params.getTlsClientAuthSubjectDn())) {
        request.setTlsClientAuthSubjectDn(params.getTlsClientAuthSubjectDn());
    }
    if (!Strings.isNullOrEmpty(params.getSubjectType())) {
        SubjectType subjectType = SubjectType.fromString(params.getSubjectType());
        if (subjectType == null) {
            LOG.error("Received invalid values in `subject_type` property. Value: " + params.getSubjectType());
            throw new HttpException(ErrorResponseCode.INVALID_SUBJECT_TYPE);
        }
        request.setSubjectType(subjectType);
    }
    if (params.getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims() != null) {
        request.setRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims(params.getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims());
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenSignedResponseAlg())) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getIdTokenSignedResponseAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `id_token_signed_response_alg` property. Value: " + params.getIdTokenSignedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        if (signatureAlgorithms == SignatureAlgorithm.NONE && !getConfigurationService().getConfiguration().getAcceptIdTokenWithoutSignature()) {
            LOG.error("`ID_TOKEN` without signature is not allowed. To allow `ID_TOKEN` without signature set `accept_id_token_without_signature` field to 'true' in client-api-server.yml.");
            throw new HttpException(ErrorResponseCode.ID_TOKEN_WITHOUT_SIGNATURE_NOT_ALLOWED);
        }
        request.setIdTokenSignedResponseAlg(signatureAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenEncryptedResponseAlg())) {
        KeyEncryptionAlgorithm keyEncryptionAlgorithms = KeyEncryptionAlgorithm.fromName(params.getIdTokenEncryptedResponseAlg());
        if (keyEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `id_token_encrypted_response_alg` property. Value: " + params.getIdTokenEncryptedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_KEY_ENCRYPTION_ALGORITHM);
        }
        request.setIdTokenEncryptedResponseAlg(keyEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getIdTokenEncryptedResponseEnc())) {
        BlockEncryptionAlgorithm blockEncryptionAlgorithms = BlockEncryptionAlgorithm.fromName(params.getIdTokenEncryptedResponseEnc());
        if (blockEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `id_token_encrypted_response_enc` property. Value: " + params.getIdTokenEncryptedResponseEnc());
            throw new HttpException(ErrorResponseCode.INVALID_BLOCK_ENCRYPTION_ALGORITHM);
        }
        request.setIdTokenEncryptedResponseEnc(blockEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getUserInfoSignedResponseAlg())) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getUserInfoSignedResponseAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `user_info_signed_response_alg` property. Value: " + params.getUserInfoSignedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        request.setUserInfoSignedResponseAlg(signatureAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getUserInfoEncryptedResponseAlg())) {
        KeyEncryptionAlgorithm keyEncryptionAlgorithms = KeyEncryptionAlgorithm.fromName(params.getUserInfoEncryptedResponseAlg());
        if (keyEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `user_info_encrypted_response_alg` property. Value: " + params.getUserInfoEncryptedResponseAlg());
            throw new HttpException(ErrorResponseCode.INVALID_KEY_ENCRYPTION_ALGORITHM);
        }
        request.setUserInfoEncryptedResponseAlg(keyEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getUserInfoEncryptedResponseEnc())) {
        BlockEncryptionAlgorithm blockEncryptionAlgorithms = BlockEncryptionAlgorithm.fromName(params.getUserInfoEncryptedResponseEnc());
        if (blockEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `user_info_encrypted_response_enc` property. Value: " + params.getUserInfoEncryptedResponseEnc());
            throw new HttpException(ErrorResponseCode.INVALID_BLOCK_ENCRYPTION_ALGORITHM);
        }
        request.setUserInfoEncryptedResponseEnc(blockEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getRequestObjectSigningAlg())) {
        SignatureAlgorithm signatureAlgorithms = SignatureAlgorithm.fromString(params.getRequestObjectSigningAlg());
        if (signatureAlgorithms == null) {
            LOG.error("Received invalid algorithm in `request_object_signing_alg` property. Value: " + params.getRequestObjectSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        request.setRequestObjectSigningAlg(signatureAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getRequestObjectEncryptionAlg())) {
        KeyEncryptionAlgorithm keyEncryptionAlgorithms = KeyEncryptionAlgorithm.fromName(params.getRequestObjectEncryptionAlg());
        if (keyEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `request_object_encryption_alg` property. Value: " + params.getRequestObjectEncryptionAlg());
            throw new HttpException(ErrorResponseCode.INVALID_KEY_ENCRYPTION_ALGORITHM);
        }
        request.setRequestObjectEncryptionAlg(keyEncryptionAlgorithms);
    }
    if (!Strings.isNullOrEmpty(params.getRequestObjectEncryptionEnc())) {
        BlockEncryptionAlgorithm blockEncryptionAlgorithms = BlockEncryptionAlgorithm.fromName(params.getRequestObjectEncryptionEnc());
        if (blockEncryptionAlgorithms == null) {
            LOG.error("Received invalid algorithm in `request_object_encryption_enc` property. Value: " + params.getRequestObjectEncryptionEnc());
            throw new HttpException(ErrorResponseCode.INVALID_BLOCK_ENCRYPTION_ALGORITHM);
        }
        request.setRequestObjectEncryptionEnc(blockEncryptionAlgorithms);
    }
    if (params.getDefaultMaxAge() != null && NumberUtils.isNumber(params.getDefaultMaxAge().toString())) {
        request.setDefaultMaxAge(params.getDefaultMaxAge());
    }
    if (params.getRequireAuthTime() != null) {
        request.setRequireAuthTime(params.getRequireAuthTime());
    }
    if (!Strings.isNullOrEmpty(params.getInitiateLoginUri())) {
        request.setInitiateLoginUri(params.getInitiateLoginUri());
    }
    if (params.getAuthorizedOrigins() != null && !params.getAuthorizedOrigins().isEmpty()) {
        request.setAuthorizedOrigins(params.getAuthorizedOrigins());
    }
    if (params.getAccessTokenLifetime() != null && NumberUtils.isNumber(params.getAccessTokenLifetime().toString())) {
        request.setAccessTokenLifetime(params.getAccessTokenLifetime());
    }
    if (!Strings.isNullOrEmpty(params.getSoftwareId())) {
        request.setSoftwareId(params.getSoftwareId());
    }
    if (!Strings.isNullOrEmpty(params.getSoftwareVersion())) {
        request.setSoftwareVersion(params.getSoftwareVersion());
    }
    if (!Strings.isNullOrEmpty(params.getSoftwareStatement())) {
        request.setSoftwareStatement(params.getSoftwareStatement());
    }
    if (params.getAllowSpontaneousScopes() != null) {
        request.setAllowSpontaneousScopes(params.getAllowSpontaneousScopes());
    }
    if (CollectionUtils.isNotEmpty(params.getSpontaneousScopes())) {
        request.setSpontaneousScopes(params.getSpontaneousScopes());
    }
    if (params.getCustomAttributes() != null && !params.getCustomAttributes().isEmpty()) {
        params.getCustomAttributes().entrySet().removeIf(entry -> entry.getKey().contains("oxAuthTrustedClient"));
        params.getCustomAttributes().entrySet().stream().forEach(e -> {
            request.addCustomAttribute(e.getKey(), e.getValue());
        });
    }
    if (StringUtils.isNotBlank(rp.getRpId())) {
        request.addCustomAttribute("rp_id", rp.getRpId());
    }
    return request;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) UpdateSiteParams(io.jans.ca.common.params.UpdateSiteParams) SubjectType(io.jans.as.model.common.SubjectType) UpdateSiteResponse(io.jans.ca.common.response.UpdateSiteResponse) Utils(io.jans.ca.server.Utils) LoggerFactory(org.slf4j.LoggerFactory) RegisterRequestMapper(io.jans.ca.server.mapper.RegisterRequestMapper) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm) HttpMethod(javax.ws.rs.HttpMethod) NumberUtils(org.apache.commons.lang.math.NumberUtils) HttpException(io.jans.ca.server.HttpException) Strings(com.google.common.base.Strings) ErrorResponseCode(io.jans.ca.common.ErrorResponseCode) IOpResponse(io.jans.ca.common.response.IOpResponse) Lists(com.google.common.collect.Lists) CollectionUtils(org.apache.commons.collections.CollectionUtils) RegisterClient(io.jans.as.client.RegisterClient) Command(io.jans.ca.common.Command) Logger(org.slf4j.Logger) Set(java.util.Set) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) RegisterRequest(io.jans.as.client.RegisterRequest) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Injector(com.google.inject.Injector) RegisterResponse(io.jans.as.client.RegisterResponse) List(java.util.List) GrantType(io.jans.as.model.common.GrantType) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) Rp(io.jans.ca.server.service.Rp) RegisterRequest(io.jans.as.client.RegisterRequest) SubjectType(io.jans.as.model.common.SubjectType) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) HttpException(io.jans.ca.server.HttpException) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)

Example 8 with Rp

use of io.jans.ca.server.service.Rp in project jans by JanssenProject.

the class GetAccessTokenByRefreshTokenOperation method execute.

@Override
public IOpResponse execute(GetAccessTokenByRefreshTokenParams params) {
    try {
        validate(params);
        final Rp rp = getRp();
        final TokenClient tokenClient = new TokenClient(getDiscoveryService().getConnectDiscoveryResponse(rp).getTokenEndpoint());
        tokenClient.setExecutor(getHttpService().getClientEngine());
        final TokenResponse tokenResponse = tokenClient.execRefreshToken(scopeAsString(params), params.getRefreshToken(), rp.getClientId(), rp.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");
        }
    } 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) HttpException(io.jans.ca.server.HttpException) GetClientTokenResponse(io.jans.ca.common.response.GetClientTokenResponse) TokenClient(io.jans.as.client.TokenClient) Rp(io.jans.ca.server.service.Rp) HttpException(io.jans.ca.server.HttpException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 9 with Rp

use of io.jans.ca.server.service.Rp in project jans by JanssenProject.

the class GetAuthorizationUrlOperation method execute.

@Override
public IOpResponse execute(GetAuthorizationUrlParams params) throws Exception {
    final Rp rp = getRp();
    String authorizationEndpoint = getDiscoveryService().getConnectDiscoveryResponse(rp).getAuthorizationEndpoint();
    List<String> scope = Lists.newArrayList();
    if (params.getScope() != null && !params.getScope().isEmpty()) {
        scope.addAll(params.getScope());
    } else if (rp.getScope() != null) {
        scope.addAll(rp.getScope());
    }
    if (StringUtils.isNotBlank(params.getRedirectUri()) && !Utils.isValidUrl(params.getRedirectUri())) {
        throw new HttpException(ErrorResponseCode.INVALID_REDIRECT_URI);
    }
    if (StringUtils.isNotBlank(params.getRedirectUri()) && !rp.getRedirectUris().contains(params.getRedirectUri())) {
        throw new HttpException(ErrorResponseCode.REDIRECT_URI_IS_NOT_REGISTERED);
    }
    List<String> responseTypes = Lists.newArrayList();
    if (params.getResponseTypes() != null && !params.getResponseTypes().isEmpty() && rp.getResponseTypes().containsAll(params.getResponseTypes())) {
        responseTypes.addAll(params.getResponseTypes());
    } else {
        responseTypes.addAll(rp.getResponseTypes());
    }
    String state = StringUtils.isNotBlank(params.getState()) ? getStateService().putState(getStateService().encodeExpiredObject(params.getState(), ExpiredObjectType.STATE)) : getStateService().generateState();
    String nonce = StringUtils.isNotBlank(params.getNonce()) ? getStateService().putNonce(getStateService().encodeExpiredObject(params.getNonce(), ExpiredObjectType.NONCE)) : getStateService().generateNonce();
    String clientId = getConfigurationService().getConfiguration().getEncodeClientIdInAuthorizationUrl() ? Utils.encode(rp.getClientId()) : rp.getClientId();
    String redirectUri = StringUtils.isNotBlank(params.getRedirectUri()) ? params.getRedirectUri() : rp.getRedirectUri();
    authorizationEndpoint += "?response_type=" + Utils.joinAndUrlEncode(responseTypes);
    authorizationEndpoint += "&client_id=" + clientId;
    authorizationEndpoint += "&redirect_uri=" + redirectUri;
    authorizationEndpoint += "&scope=" + Utils.joinAndUrlEncode(scope);
    authorizationEndpoint += "&state=" + state;
    authorizationEndpoint += "&nonce=" + nonce;
    String acrValues = Utils.joinAndUrlEncode(acrValues(rp, params)).trim();
    if (!Strings.isNullOrEmpty(acrValues)) {
        authorizationEndpoint += "&acr_values=" + acrValues;
    }
    if (!Strings.isNullOrEmpty(params.getPrompt())) {
        authorizationEndpoint += "&prompt=" + params.getPrompt();
    }
    if (!Strings.isNullOrEmpty(params.getHostedDomain())) {
        authorizationEndpoint += "&hd=" + params.getHostedDomain();
    }
    if (params.getCustomParameters() != null && !params.getCustomParameters().isEmpty()) {
        authorizationEndpoint += "&" + AuthorizeRequestParam.CUSTOM_RESPONSE_HEADERS + "=" + Utils.encode(Util.mapAsString(params.getCustomParameters()));
    }
    if (params.getParams() != null && !params.getParams().isEmpty()) {
        authorizationEndpoint += "&" + Utils.mapAsStringWithEncodedValues(params.getParams());
    }
    return new GetAuthorizationUrlResponse(authorizationEndpoint);
}
Also used : GetAuthorizationUrlResponse(io.jans.ca.common.response.GetAuthorizationUrlResponse) HttpException(io.jans.ca.server.HttpException) Rp(io.jans.ca.server.service.Rp)

Example 10 with Rp

use of io.jans.ca.server.service.Rp 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)

Aggregations

Rp (io.jans.ca.server.service.Rp)28 HttpException (io.jans.ca.server.HttpException)13 Injector (com.google.inject.Injector)4 OpenIdConfigurationResponse (io.jans.as.client.OpenIdConfigurationResponse)4 RegisterRequest (io.jans.as.client.RegisterRequest)4 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)4 Jwt (io.jans.as.model.jwt.Jwt)4 UmaMetadata (io.jans.as.model.uma.UmaMetadata)4 IOpResponse (io.jans.ca.common.response.IOpResponse)4 Lists (com.google.common.collect.Lists)3 Command (io.jans.ca.common.Command)3 ErrorResponseCode (io.jans.ca.common.ErrorResponseCode)3 RegisterSiteResponse (io.jans.ca.common.response.RegisterSiteResponse)3 Utils (io.jans.ca.server.Utils)3 List (java.util.List)3 StringUtils (org.apache.commons.lang.StringUtils)3 Test (org.testng.annotations.Test)3 Strings (com.google.common.base.Strings)2 Sets (com.google.common.collect.Sets)2 RegisterClient (io.jans.as.client.RegisterClient)2