Search in sources :

Example 26 with HttpException

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

the class RegisterSiteOperation method registerClient.

private RegisterResponse registerClient(RegisterSiteParams params, RegisterRequest request) {
    String opHostEndpoint = Strings.isNullOrEmpty(params.getOpConfigurationEndpoint()) ? params.getOpHost() : params.getOpConfigurationEndpoint();
    Preconditions.checkState(!Strings.isNullOrEmpty(opHostEndpoint), "Both op_configuration_endpoint and op_host contains blank value. Please specify valid OP public address.");
    final String registrationEndpoint = getDiscoveryService().getConnectDiscoveryResponse(params.getOpConfigurationEndpoint(), params.getOpHost(), params.getOpDiscoveryPath()).getRegistrationEndpoint();
    if (Strings.isNullOrEmpty(registrationEndpoint)) {
        LOG.error("This OP (" + opHostEndpoint + ") does not provide registration_endpoint. It means that jans_client_api is not able dynamically register client. " + "Therefore it is required to obtain/register client manually on OP site and provide client_id and client_secret to jans_client_api register_site command.");
        throw new HttpException(ErrorResponseCode.NO_REGISTRATION_ENDPOINT);
    }
    final RegisterClient registerClient = getOpClientFactory().createRegisterClient(registrationEndpoint);
    registerClient.setRequest(request);
    registerClient.setExecutor(getHttpService().getClientEngine());
    final RegisterResponse response = registerClient.exec();
    if (response != null) {
        if (!Strings.isNullOrEmpty(response.getClientId()) && !Strings.isNullOrEmpty(response.getClientSecret())) {
            LOG.trace("Registered client for site - client_id: " + response.getClientId() + ", claims: " + response.getClaims() + ", registration_client_uri:" + response.getRegistrationClientUri());
            return response;
        }
        LOG.error("ClientId: " + response.getClientId() + ", clientSecret: " + response.getClientSecret());
        if (Strings.isNullOrEmpty(response.getClientId())) {
            LOG.error("`client_id` is not returned from OP host. Please check OP log file for error (oxauth.log).");
            throw new HttpException(ErrorResponseCode.NO_CLIENT_ID_RETURNED);
        }
        if (Strings.isNullOrEmpty(response.getClientSecret())) {
            LOG.error("`client_secret` is not returned from OP host. Please check: 1) OP log file for error (oxauth.log) 2) whether `returnClientSecretOnRead` configuration property is set to true on OP host.");
            throw new HttpException(ErrorResponseCode.NO_CLIENT_SECRET_RETURNED);
        }
    } else {
        LOG.error("RegisterClient response is null.");
    }
    if (response != null && !Strings.isNullOrEmpty(response.getErrorDescription())) {
        LOG.error(response.getErrorDescription());
    }
    throw new RuntimeException("Failed to register client for site. Details: " + (response != null ? response.getEntity() : "response is null"));
}
Also used : RegisterResponse(io.jans.as.client.RegisterResponse) RegisterClient(io.jans.as.client.RegisterClient) HttpException(io.jans.ca.server.HttpException)

Example 27 with HttpException

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

the class UmaTokenService method getRpt.

public RpGetRptResponse getRpt(RpGetRptParams params) throws Exception {
    Rp rp = rpSyncService.getRp(params.getRpId());
    UmaMetadata discovery = discoveryService.getUmaDiscoveryByRpId(params.getRpId());
    if (!Strings.isNullOrEmpty(rp.getRpt()) && rp.getRptExpiresAt() != null) {
        if (!CoreUtils.isExpired(rp.getRptExpiresAt())) {
            LOG.debug("RPT from rp, RPT: " + rp.getRpt() + ", rp: " + rp);
            RpGetRptResponse result = new RpGetRptResponse();
            result.setRpt(rp.getRpt());
            result.setTokenType(rp.getRptTokenType());
            result.setPct(rp.getRptPct());
            result.setUpdated(rp.getRptUpgraded());
            return result;
        }
    }
    Builder client = opClientFactory.createClientRequest(discovery.getTokenEndpoint(), httpService.getClientEngine());
    client.header("Authorization", "Basic " + Utils.encodeCredentials(rp.getClientId(), rp.getClientSecret()));
    Form formRequest = new Form();
    formRequest.param("grant_type", GrantType.OXAUTH_UMA_TICKET.getValue());
    formRequest.param("ticket", params.getTicket());
    if (params.getClaimToken() != null) {
        formRequest.param("claim_token", params.getClaimToken());
    }
    if (params.getClaimTokenFormat() != null) {
        formRequest.param("claim_token_format", params.getClaimTokenFormat());
    }
    if (params.getPct() != null) {
        formRequest.param("pct", params.getPct());
    }
    if (params.getRpt() != null) {
        formRequest.param("rpt", params.getRpt());
    }
    if (params.getScope() != null) {
        formRequest.param("scope", Utils.joinAndUrlEncode(params.getScope()));
    }
    if (params.getParams() != null && !params.getParams().isEmpty()) {
        for (Map.Entry<String, String> p : params.getParams().entrySet()) {
            formRequest.param(p.getKey(), p.getValue());
        }
    }
    Response response = null;
    try {
        response = client.buildPost(Entity.form(formRequest)).invoke();
    } catch (Exception e) {
        LOG.error("Failed to receive RPT response for rp: " + rp, e);
        throw new HttpException(ErrorResponseCode.FAILED_TO_GET_RPT);
    }
    String entityResponse = null;
    try {
        entityResponse = response.readEntity(String.class);
    } catch (Exception e) {
        LOG.error("Failed to read RPT response for rp: " + rp, e);
        throw new HttpException(ErrorResponseCode.FAILED_TO_GET_RPT);
    } finally {
        response.close();
    }
    UmaTokenResponse tokenResponse = asTokenResponse(entityResponse);
    if (tokenResponse != null && StringUtils.isNotBlank(tokenResponse.getAccessToken())) {
        final IntrospectionService introspectionService = ServerLauncher.getInjector().getInstance(IntrospectionService.class);
        CorrectRptIntrospectionResponse status = introspectionService.introspectRpt(params.getRpId(), tokenResponse.getAccessToken());
        LOG.debug("RPT " + tokenResponse.getAccessToken() + ", status: " + status);
        if (status.getActive()) {
            LOG.debug("RPT is successfully obtained from AS. RPT: {}", tokenResponse.getAccessToken());
            rp.setRpt(tokenResponse.getAccessToken());
            rp.setRptTokenType(tokenResponse.getTokenType());
            rp.setRptPct(tokenResponse.getPct());
            rp.setRptUpgraded(tokenResponse.getUpgraded());
            rp.setRptCreatedAt(new Date(status.getIssuedAt() * 1000));
            rp.setRptExpiresAt(new Date(status.getExpiresAt() * 1000));
            rpService.updateSilently(rp);
            RpGetRptResponse result = new RpGetRptResponse();
            result.setRpt(rp.getRpt());
            result.setTokenType(rp.getRptTokenType());
            result.setPct(rp.getRptPct());
            result.setUpdated(rp.getRptUpgraded());
            return result;
        }
    } else {
        RpGetRptOperation.handleRptError(response.getStatus(), entityResponse);
    }
    LOG.error("Failed to get RPT for rp: " + rp);
    throw new HttpException(ErrorResponseCode.FAILED_TO_GET_RPT);
}
Also used : CorrectRptIntrospectionResponse(io.jans.ca.common.introspection.CorrectRptIntrospectionResponse) UmaTokenResponse(io.jans.as.model.uma.UmaTokenResponse) Form(javax.ws.rs.core.Form) Builder(javax.ws.rs.client.Invocation.Builder) HttpException(io.jans.ca.server.HttpException) IOException(java.io.IOException) RpGetRptResponse(io.jans.ca.common.response.RpGetRptResponse) CorrectRptIntrospectionResponse(io.jans.ca.common.introspection.CorrectRptIntrospectionResponse) UmaTokenResponse(io.jans.as.model.uma.UmaTokenResponse) Response(javax.ws.rs.core.Response) UmaMetadata(io.jans.as.model.uma.UmaMetadata) HttpException(io.jans.ca.server.HttpException) RpGetRptResponse(io.jans.ca.common.response.RpGetRptResponse)

Example 28 with HttpException

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

the class ValidationService method introspect.

public IntrospectionResponse introspect(String accessToken, String rpId) {
    if (StringUtils.isBlank(accessToken)) {
        LOG.debug("access_token is blank. Command is protected by access_token, please provide valid token or otherwise switch off protection in configuration with protect_commands_with_access_token=false");
        throw new HttpException(ErrorResponseCode.BLANK_ACCESS_TOKEN);
    }
    final RpSyncService rpSyncService = ServerLauncher.getInjector().getInstance(RpSyncService.class);
    final Rp rp = rpSyncService.getRp(rpId);
    LOG.trace("Introspect token with rp: " + rp);
    final IntrospectionService introspectionService = ServerLauncher.getInjector().getInstance(IntrospectionService.class);
    final IntrospectionResponse response = introspectionService.introspectToken(rpId, accessToken);
    if (!response.isActive()) {
        LOG.error("access_token is not active.");
        throw new HttpException(ErrorResponseCode.INACTIVE_ACCESS_TOKEN);
    }
    return response;
}
Also used : IntrospectionResponse(io.jans.as.model.common.IntrospectionResponse) HttpException(io.jans.ca.server.HttpException)

Example 29 with HttpException

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

the class ValidationService method validateAccessToken.

/**
 * Returns whether has valid token
 *
 * @param accessToken
 * @param rpId
 */
public void validateAccessToken(String accessToken, String rpId) {
    if (StringUtils.isBlank(accessToken)) {
        throw new HttpException(ErrorResponseCode.BLANK_ACCESS_TOKEN);
    }
    final RpSyncService rpSyncService = ServerLauncher.getInjector().getInstance(RpSyncService.class);
    final Rp rp = rpSyncService.getRp(rpId);
    final IntrospectionResponse introspectionResponse = introspect(accessToken, rpId);
    LOG.trace("access_token: " + accessToken + ", introspection: " + introspectionResponse + ", clientId: " + rp.getClientId());
    if (StringUtils.isBlank(introspectionResponse.getClientId())) {
        LOG.error("AS returned introspection response with empty/blank client_id which is required by jans_client_api. Please check your AS installation and make sure AS return client_id for introspection call (CE 3.1.0 or later).");
        throw new HttpException(ErrorResponseCode.NO_CLIENT_ID_IN_INTROSPECTION_RESPONSE);
    }
    if (!introspectionResponse.getScope().contains("jans_client_api")) {
        LOG.error("access_token does not have `jans_client_api` scope. Make sure a) scope exists on AS b) register_site is registered with 'jans_client_api' scope c) get_client_token has 'jans_client_api' scope in request");
        throw new HttpException(ErrorResponseCode.ACCESS_TOKEN_INSUFFICIENT_SCOPE);
    }
    if (introspectionResponse.getClientId().equals(rp.getClientId())) {
        return;
    }
    LOG.error("No access token provided in Authorization header. Forbidden.");
    throw new HttpException(ErrorResponseCode.INVALID_ACCESS_TOKEN);
}
Also used : IntrospectionResponse(io.jans.as.model.common.IntrospectionResponse) HttpException(io.jans.ca.server.HttpException)

Example 30 with HttpException

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

the class Validator method createJwsSigner.

public static AbstractJwsSigner createJwsSigner(Jwt idToken, OpenIdConfigurationResponse discoveryResponse, PublicOpKeyService keyService, OpClientFactory opClientFactory, Rp rp, RpServerConfiguration configuration) {
    final String algorithm = idToken.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
    final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm);
    final String jwkUrl = discoveryResponse.getJwksUri();
    String kid = idToken.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
    if (signatureAlgorithm == null)
        throw new HttpException(ErrorResponseCode.INVALID_ALGORITHM);
    if (Strings.isNullOrEmpty(kid) && (signatureAlgorithm.getFamily() == AlgorithmFamily.RSA || signatureAlgorithm.getFamily() == AlgorithmFamily.EC)) {
        LOG.warn("Warning:`kid` is missing in id_token header. oxd will throw error if RP is unable to determine the key to used for `id_token` validation.");
    }
    if (signatureAlgorithm == SignatureAlgorithm.NONE) {
        if (!configuration.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);
        }
        return new AbstractJwsSigner(signatureAlgorithm) {

            @Override
            public String generateSignature(String signingInput) throws SignatureException {
                return null;
            }

            @Override
            public boolean validateSignature(String signingInput, String signature) throws SignatureException {
                return true;
            }
        };
    } else if (signatureAlgorithm.getFamily() == AlgorithmFamily.RSA) {
        final RSAPublicKey publicKey = (RSAPublicKey) keyService.getPublicKey(jwkUrl, kid, signatureAlgorithm, Use.SIGNATURE);
        return opClientFactory.createRSASigner(signatureAlgorithm, publicKey);
    } else if (signatureAlgorithm.getFamily() == AlgorithmFamily.HMAC) {
        return new HMACSigner(signatureAlgorithm, rp.getClientSecret());
    } else if (signatureAlgorithm.getFamily() == AlgorithmFamily.EC) {
        final ECDSAPublicKey publicKey = (ECDSAPublicKey) keyService.getPublicKey(jwkUrl, kid, signatureAlgorithm, Use.SIGNATURE);
        return new ECDSASigner(signatureAlgorithm, publicKey);
    }
    throw new HttpException(ErrorResponseCode.ALGORITHM_NOT_SUPPORTED);
}
Also used : RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) HMACSigner(io.jans.as.model.jws.HMACSigner) ECDSASigner(io.jans.as.model.jws.ECDSASigner) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) HttpException(io.jans.ca.server.HttpException) AbstractJwsSigner(io.jans.as.model.jws.AbstractJwsSigner) ECDSAPublicKey(io.jans.as.model.crypto.signature.ECDSAPublicKey)

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