Search in sources :

Example 1 with OpenIdConfigurationResponse

use of io.jans.as.client.OpenIdConfigurationResponse in project jans by JanssenProject.

the class ConfigurationRestWebServiceHttpTest method requestOpenIdConfiguration.

@Test
@Parameters({ "swdResource" })
public void requestOpenIdConfiguration(final String resource) throws Exception {
    showTitle("OpenID Connect Discovery");
    OpenIdConnectDiscoveryClient openIdConnectDiscoveryClient = new OpenIdConnectDiscoveryClient(resource);
    CloseableHttpClient httpClient = createHttpClient(HostnameVerifierType.ALLOW_ALL);
    OpenIdConnectDiscoveryResponse openIdConnectDiscoveryResponse;
    try {
        openIdConnectDiscoveryResponse = openIdConnectDiscoveryClient.exec(new ApacheHttpClient43Engine(httpClient));
    } finally {
        httpClient.close();
    }
    showClient(openIdConnectDiscoveryClient);
    assertEquals(openIdConnectDiscoveryResponse.getStatus(), 200, "Unexpected response code");
    assertNotNull(openIdConnectDiscoveryResponse.getSubject());
    assertTrue(openIdConnectDiscoveryResponse.getLinks().size() > 0);
    String configurationEndpoint = openIdConnectDiscoveryResponse.getLinks().get(0).getHref() + "/.well-known/openid-configuration";
    showTitle("OpenID Connect Configuration");
    OpenIdConfigurationClient client = new OpenIdConfigurationClient(configurationEndpoint);
    OpenIdConfigurationResponse response = client.execOpenIdConfiguration();
    showClient(client);
    assertEquals(response.getStatus(), 200, "Unexpected response code");
    assertNotNull(response.getIssuer(), "The issuer is null");
    assertNotNull(response.getAuthorizationEndpoint(), "The authorizationEndpoint is null");
    assertNotNull(response.getTokenEndpoint(), "The tokenEndpoint is null");
    assertNotNull(response.getRevocationEndpoint(), "The tokenRevocationEndpoint is null");
    assertNotNull(response.getUserInfoEndpoint(), "The userInfoEndPoint is null");
    assertNotNull(response.getClientInfoEndpoint(), "The clientInfoEndPoint is null");
    assertNotNull(response.getCheckSessionIFrame(), "The checkSessionIFrame is null");
    assertNotNull(response.getEndSessionEndpoint(), "The endSessionEndpoint is null");
    assertNotNull(response.getJwksUri(), "The jwksUri is null");
    assertNotNull(response.getRegistrationEndpoint(), "The registrationEndpoint is null");
    assertNotNull(response.getIntrospectionEndpoint(), "The introspectionEndpoint is null");
    assertNotNull(response.getParEndpoint(), "The parEndpoint is null");
    assertTrue(response.getScopesSupported().size() > 0, "The scopesSupported is empty");
    assertTrue(response.getScopeToClaimsMapping().size() > 0, "The scope to claims mapping is empty");
    assertTrue(response.getResponseTypesSupported().size() > 0, "The responseTypesSupported is empty");
    assertTrue(response.getResponseModesSupported().size() > 0, "The responseModesSupported is empty");
    assertTrue(response.getGrantTypesSupported().size() > 0, "The grantTypesSupported is empty");
    assertTrue(response.getAcrValuesSupported().size() >= 0, "The acrValuesSupported is empty");
    assertTrue(response.getSubjectTypesSupported().size() > 0, "The subjectTypesSupported is empty");
    assertTrue(response.getUserInfoSigningAlgValuesSupported().size() > 0, "The userInfoSigningAlgValuesSupported is empty");
    assertTrue(response.getUserInfoEncryptionAlgValuesSupported().size() > 0, "The userInfoEncryptionAlgValuesSupported is empty");
    assertTrue(response.getUserInfoEncryptionEncValuesSupported().size() > 0, "The userInfoEncryptionEncValuesSupported is empty");
    assertTrue(response.getIdTokenSigningAlgValuesSupported().size() > 0, "The idTokenSigningAlgValuesSupported is empty");
    assertTrue(response.getIdTokenEncryptionAlgValuesSupported().size() > 0, "The idTokenEncryptionAlgValuesSupported is empty");
    assertTrue(response.getIdTokenEncryptionEncValuesSupported().size() > 0, "The idTokenEncryptionEncValuesSupported is empty");
    assertTrue(response.getRequestObjectSigningAlgValuesSupported().size() > 0, "The requestObjectSigningAlgValuesSupported is empty");
    assertTrue(response.getRequestObjectEncryptionAlgValuesSupported().size() > 0, "The requestObjectEncryptionAlgValuesSupported is empty");
    assertTrue(response.getRequestObjectEncryptionEncValuesSupported().size() > 0, "The requestObjectEncryptionEncValuesSupported is empty");
    assertTrue(response.getTokenEndpointAuthMethodsSupported().size() > 0, "The tokenEndpointAuthMethodsSupported is empty");
    assertTrue(response.getTokenEndpointAuthSigningAlgValuesSupported().size() > 0, "The tokenEndpointAuthSigningAlgValuesSupported is empty");
    assertTrue(response.getDisplayValuesSupported().size() > 0, "The displayValuesSupported is empty");
    assertTrue(response.getClaimTypesSupported().size() > 0, "The claimTypesSupported is empty");
    assertTrue(response.getClaimsSupported().size() > 0, "The claimsSupported is empty");
    assertNotNull(response.getServiceDocumentation(), "The serviceDocumentation is null");
    assertTrue(response.getClaimsLocalesSupported().size() > 0, "The claimsLocalesSupported is empty");
    assertTrue(response.getUiLocalesSupported().size() > 0, "The uiLocalesSupported is empty");
    assertTrue(response.getClaimsParameterSupported(), "The claimsParameterSupported is false");
    assertTrue(response.getRequestParameterSupported(), "The requestParameterSupported is false");
    assertTrue(response.getRequestUriParameterSupported(), "The requestUriParameterSupported is false");
    assertFalse(response.getRequireRequestUriRegistration(), "The requireRequestUriRegistration is true");
    assertNotNull(response.getOpPolicyUri(), "The opPolicyUri is null");
    assertNotNull(response.getOpTosUri(), "The opTosUri is null");
    // Jans Auth #917: Add dynamic scopes and claims to discovery
    Map<String, List<String>> scopeToClaims = response.getScopeToClaimsMapping();
    List<String> scopesSupported = response.getScopesSupported();
    List<String> claimsSupported = response.getClaimsSupported();
    for (Map.Entry<String, List<String>> scopeEntry : scopeToClaims.entrySet()) {
        assertTrue(scopesSupported.contains(scopeEntry.getKey()), "The scopes supported list does not contain the scope: " + scopeEntry.getKey());
        for (String claimEntry : scopeEntry.getValue()) {
            assertTrue(claimsSupported.contains(claimEntry), "The claims supported list does not contain the claim: " + claimEntry);
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) OpenIdConnectDiscoveryClient(io.jans.as.client.OpenIdConnectDiscoveryClient) OpenIdConfigurationClient(io.jans.as.client.OpenIdConfigurationClient) OpenIdConnectDiscoveryResponse(io.jans.as.client.OpenIdConnectDiscoveryResponse) OpenIdConfigurationResponse(io.jans.as.client.OpenIdConfigurationResponse) List(java.util.List) Map(java.util.Map) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine) Parameters(org.testng.annotations.Parameters) BaseTest(io.jans.as.client.BaseTest) Test(org.testng.annotations.Test)

Example 2 with OpenIdConfigurationResponse

use of io.jans.as.client.OpenIdConfigurationResponse in project jans by JanssenProject.

the class CheckAccessTokenOperation method execute.

@Override
public IOpResponse execute(CheckAccessTokenParams params) throws Exception {
    final OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponseByRpId(params.getRpId());
    final String idToken = params.getIdToken();
    final String accessToken = params.getAccessToken();
    final Jwt jwt = Jwt.parse(idToken);
    final Date issuedAt = jwt.getClaims().getClaimAsDate(JwtClaimName.ISSUED_AT);
    final Date expiresAt = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
    final CheckAccessTokenResponse opResponse = new CheckAccessTokenResponse();
    opResponse.setActive(isAccessTokenValid(accessToken, jwt, discoveryResponse));
    opResponse.setIssuedAt(issuedAt);
    opResponse.setExpiresAt(expiresAt);
    return opResponse;
}
Also used : Jwt(io.jans.as.model.jwt.Jwt) CheckAccessTokenResponse(io.jans.ca.common.response.CheckAccessTokenResponse) OpenIdConfigurationResponse(io.jans.as.client.OpenIdConfigurationResponse) Date(java.util.Date)

Example 3 with OpenIdConfigurationResponse

use of io.jans.as.client.OpenIdConfigurationResponse in project jans by JanssenProject.

the class DiscoveryService method getConnectDiscoveryResponse.

public OpenIdConfigurationResponse getConnectDiscoveryResponse(String opConfigurationEndpoint) {
    validationService.validateOpConfigurationEndpoint(opConfigurationEndpoint);
    try {
        final OpenIdConfigurationResponse r = map.get(opConfigurationEndpoint);
        if (r != null) {
            validationService.isOpHostAllowed(r.getIssuer());
            return r;
        }
        final OpenIdConfigurationClient client = opClientFactory.createOpenIdConfigurationClient(opConfigurationEndpoint);
        client.setExecutor(httpService.getClientEngine());
        final OpenIdConfigurationResponse response = client.execOpenIdConfiguration();
        LOG.trace("Discovery response: {} ", response.getEntity());
        if (StringUtils.isNotBlank(response.getEntity())) {
            map.put(opConfigurationEndpoint, response);
            validationService.isOpHostAllowed(response.getIssuer());
            return response;
        } else {
            LOG.error("No response from discovery!");
        }
    } catch (SSLHandshakeException e) {
        LOG.error(e.getMessage(), e);
        throw new HttpException(ErrorResponseCode.SSL_HANDSHAKE_ERROR);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal server error. Message: " + e.getMessage()).build());
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    LOG.error("Unable to fetch discovery information for op_configuration_endpoint: {}", opConfigurationEndpoint);
    throw new HttpException(ErrorResponseCode.NO_CONNECT_DISCOVERY_RESPONSE);
}
Also used : OpenIdConfigurationClient(io.jans.as.client.OpenIdConfigurationClient) WebApplicationException(javax.ws.rs.WebApplicationException) OpenIdConfigurationResponse(io.jans.as.client.OpenIdConfigurationResponse) HttpException(io.jans.ca.server.HttpException) IOException(java.io.IOException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) HttpException(io.jans.ca.server.HttpException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 4 with OpenIdConfigurationResponse

use of io.jans.as.client.OpenIdConfigurationResponse 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 5 with OpenIdConfigurationResponse

use of io.jans.as.client.OpenIdConfigurationResponse 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

OpenIdConfigurationResponse (io.jans.as.client.OpenIdConfigurationResponse)14 OpenIdConfigurationClient (io.jans.as.client.OpenIdConfigurationClient)7 HttpException (io.jans.ca.server.HttpException)6 Test (org.testng.annotations.Test)5 BaseTest (io.jans.as.client.BaseTest)4 OpenIdConnectDiscoveryClient (io.jans.as.client.OpenIdConnectDiscoveryClient)4 OpenIdConnectDiscoveryResponse (io.jans.as.client.OpenIdConnectDiscoveryResponse)4 Jwt (io.jans.as.model.jwt.Jwt)4 Rp (io.jans.ca.server.service.Rp)4 ApacheHttpClient43Engine (org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine)4 Parameters (org.testng.annotations.Parameters)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 POJOResponse (io.jans.ca.common.response.POJOResponse)2 JwkClient (io.jans.as.client.JwkClient)1 JwkResponse (io.jans.as.client.JwkResponse)1 TokenClient (io.jans.as.client.TokenClient)1 TokenRequest (io.jans.as.client.TokenRequest)1 TokenResponse (io.jans.as.client.TokenResponse)1 AuthenticationMethod (io.jans.as.model.common.AuthenticationMethod)1 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)1