org.gluu.oxauth.client.OpenIdConfigurationResponse Java Examples

The following examples show how to use org.gluu.oxauth.client.OpenIdConfigurationResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenIdService.java    From oxTrust with MIT License 6 votes vote down vote up
private void loadOpenIdConfiguration() throws IOException {
    String openIdProvider = appConfiguration.getOxAuthIssuer();
    if (StringHelper.isEmpty(openIdProvider)) {
        throw new ConfigurationException("OpenIdProvider Url is invalid");
    }

    openIdProvider = openIdProvider + "/.well-known/openid-configuration";

    final OpenIdConfigurationClient openIdConfigurationClient = new OpenIdConfigurationClient(openIdProvider);
    final OpenIdConfigurationResponse response = openIdConfigurationClient.execOpenIdConfiguration();
    if ((response == null) || (response.getStatus() != 200)) {
        throw new ConfigurationException("Failed to load oxAuth configuration");
    }

    log.info("Successfully loaded oxAuth configuration");

    this.openIdConfiguration = response;
}
 
Example #2
Source File: ValidateOperation.java    From oxd with Apache License 2.0 6 votes vote down vote up
@Override
public IOpResponse execute(ValidateParams params) throws Exception {
    validateParams(params);

    Rp rp = getRp();
    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponseByOxdId(params.getOxdId());

    final Jwt idToken = Jwt.parse(params.getIdToken());

    final Validator validator = new Validator.Builder()
            .discoveryResponse(discoveryResponse)
            .idToken(idToken)
            .keyService(getKeyService())
            .opClientFactory(getOpClientFactory())
            .oxdServerConfiguration(getConfigurationService().getConfiguration())
            .rp(rp)
            .build();
    validator.validateNonce(getStateService());
    validator.validateIdToken(rp.getClientId());
    validator.validateAccessToken(params.getAccessToken());
    validator.validateAuthorizationCode(params.getCode());

    return new POJOResponse("");
}
 
Example #3
Source File: OpenIdClient.java    From oxTrust with MIT License 6 votes vote down vote up
private void loadOpenIdConfiguration() throws IOException {
	String openIdProvider = appConfiguration.getOpenIdProviderUrl();
	if (StringHelper.isEmpty(openIdProvider)) {
		throw new ConfigurationException("OpenIdProvider Url is invalid");
	}

	final OpenIdConfigurationClient openIdConfigurationClient = new OpenIdConfigurationClient(openIdProvider);
	final OpenIdConfigurationResponse response = openIdConfigurationClient.execOpenIdConfiguration();
	if ((response == null) || (response.getStatus() != 200)) {
		throw new ConfigurationException("Failed to load oxAuth configuration");
	}

	logger.info("Successfully loaded oxAuth configuration");

	this.openIdConfiguration = response;
}
 
Example #4
Source File: CheckAccessTokenOperation.java    From oxd with Apache License 2.0 6 votes vote down vote up
private boolean isAccessTokenValid(String p_accessToken, Jwt jwt, OpenIdConfigurationResponse discoveryResponse) {
    try {
        //                final String type = jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE);
        final String algorithm = jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        final String jwkUrl = discoveryResponse.getJwksUri();
        final String kid = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);

        final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm);

        final RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwkUrl, kid);
        final RSASigner rsaSigner = new RSASigner(signatureAlgorithm, publicKey);
        return rsaSigner.validateAccessToken(p_accessToken, jwt);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return false;
    }
}
 
Example #5
Source File: CheckAccessTokenOperation.java    From oxd with Apache License 2.0 6 votes vote down vote up
@Override
public IOpResponse execute(CheckAccessTokenParams params) throws Exception {
    final OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponseByOxdId(params.getOxdId());
    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;
}
 
Example #6
Source File: oxAuthDiscoveryTest.java    From oxd with Apache License 2.0 5 votes vote down vote up
@Test
public void discoveryCallByOxAuthClient() throws IOException {
    String url = "https://ce-dev.gluu.org/.well-known/openid-configuration";
    OpenIdConfigurationClient client = new OpenIdConfigurationClient(url);
    OpenIdConfigurationResponse response = client.execOpenIdConfiguration();
    System.out.println(response.getEntity());
    assertNotNull(response);
}
 
Example #7
Source File: GetDiscoveryOperation.java    From oxd with Apache License 2.0 5 votes vote down vote up
public IOpResponse execute(GetDiscoveryParams params) {
    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(params.getOpConfigurationEndpoint(), params.getOpHost(), params.getOpDiscoveryPath());

    GetDiscoveryResponse response = new GetDiscoveryResponse();
    try {
        BeanUtils.copyProperties(response, discoveryResponse);
        return response;
    } catch (IllegalAccessException | InvocationTargetException e) {
        LOG.error("Error in creating op discovery configuration response ", e);
    }
    throw new HttpException(ErrorResponseCode.FAILED_TO_GET_DISCOVERY);
}
 
Example #8
Source File: GetLogoutUrlOperation.java    From oxd with Apache License 2.0 5 votes vote down vote up
@Override
public IOpResponse execute(GetLogoutUrlParams params) throws Exception {
    final Rp rp = getRp();

    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(rp);
    String endSessionEndpoint = discoveryResponse.getEndSessionEndpoint();

    String postLogoutRedirectUrl = params.getPostLogoutRedirectUri();
    if (Strings.isNullOrEmpty(postLogoutRedirectUrl)) {
        postLogoutRedirectUrl = rp.getPostLogoutRedirectUri();
    }
    if (Strings.isNullOrEmpty(postLogoutRedirectUrl)) {
        postLogoutRedirectUrl = "";
    }

    if (Strings.isNullOrEmpty(endSessionEndpoint)) {
        if (rp.getOpHost().startsWith(GOOGLE_OP_HOST) && getInstance(ConfigurationService.class).get().getSupportGoogleLogout()) {
            String logoutUrl = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=" + postLogoutRedirectUrl;
            return new GetLogoutUriResponse(logoutUrl);
        }

        LOG.error("Failed to get end_session_endpoint at: " + getDiscoveryService().getConnectDiscoveryUrl(rp));
        throw new HttpException(ErrorResponseCode.FAILED_TO_GET_END_SESSION_ENDPOINT);
    }

    String uri = endSessionEndpoint;
    if (!Strings.isNullOrEmpty(postLogoutRedirectUrl)) {
        uri += separator(uri) + "post_logout_redirect_uri=" + URLEncoder.encode(postLogoutRedirectUrl, "UTF-8");
    }
    if (!Strings.isNullOrEmpty(params.getState())) {
        uri += separator(uri) + "state=" + params.getState();
    }
    if (!Strings.isNullOrEmpty(params.getSessionState())) {
        uri += separator(uri) + "session_state=" + params.getSessionState();
    }

    return new GetLogoutUriResponse(uri);
}
 
Example #9
Source File: Validator.java    From oxd with Apache License 2.0 4 votes vote down vote up
public OpenIdConfigurationResponse getDiscoveryResponse() {
    return discoveryResponse;
}
 
Example #10
Source File: ConfigurationRestWebServiceHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@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 ApacheHttpClient4Executor(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.getIdGenerationEndpoint(), "The idGenerationEndpoint 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");

      // oxAuth #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);
          }
      }
  }
 
Example #11
Source File: ConfigurationTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Test
@Parameters({"swdResource"})
public void requestOpenIdConfiguration(final String resource) throws Exception {
    showTitle("OpenID Connect Discovery");

    OpenIdConnectDiscoveryClient openIdConnectDiscoveryClient = new OpenIdConnectDiscoveryClient(resource);
    OpenIdConnectDiscoveryResponse openIdConnectDiscoveryResponse = openIdConnectDiscoveryClient.exec(
            new ApacheHttpClient4Executor(createHttpClient(HostnameVerifierType.ALLOW_ALL)));

    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.getEndSessionEndpoint(), "The endSessionEndpoint is null");
    assertNotNull(response.getJwksUri(), "The jwksUri is null");
    assertNotNull(response.getRegistrationEndpoint(), "The registrationEndpoint is null");

    assertTrue(response.getGrantTypesSupported().size() > 0, "The grantTypesSupported is empty");
    assertTrue(response.getGrantTypesSupported().contains(GrantType.CIBA.getParamName()), "The grantTypes urn:openid:params:grant-type:ciba is null");

    assertNotNull(response.getBackchannelAuthenticationEndpoint(), "The backchannelAuthenticationEndpoint is null");
    assertTrue(response.getBackchannelTokenDeliveryModesSupported().size() > 0, "The backchannelTokenDeliveryModesSupported is empty");
    assertTrue(response.getBackchannelAuthenticationRequestSigningAlgValuesSupported().size() > 0, "The backchannelAuthenticationRequestSigningAlgValuesSupported is empty");
    assertNotNull(response.getBackchannelUserCodeParameterSupported(), "The backchannelUserCodeParameterSupported is null");
}
 
Example #12
Source File: OpenIdClient.java    From oxTrust with MIT License 4 votes vote down vote up
public OpenIdConfigurationResponse getOpenIdConfiguration() {
	return openIdConfiguration;
}
 
Example #13
Source File: Authenticator.java    From oxTrust with MIT License 4 votes vote down vote up
private String requestAccessToken(String oxAuthHost, String authorizationCode, String sessionState, String scopes,
		String clientID, String clientPassword) {
	OpenIdConfigurationResponse openIdConfiguration = openIdService.getOpenIdConfiguration();
	// 1. Request access token using the authorization code.
	TokenClient tokenClient1 = new TokenClient(openIdConfiguration.getTokenEndpoint());

	log.info("Sending request to token endpoint");
	String redirectURL = appConfiguration.getLoginRedirectUrl();
	log.info("redirectURI : " + redirectURL);
	TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, redirectURL, clientID,
			clientPassword);

	log.debug(" tokenResponse : " + tokenResponse);
	if (tokenResponse == null) {
		log.error("Get empty token response. User rcan't log into application");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	log.debug(" tokenResponse.getErrorType() : " + tokenResponse.getErrorType());

	String accessToken = tokenResponse.getAccessToken();
	log.debug(" accessToken : " + accessToken);

	String idToken = tokenResponse.getIdToken();
	log.debug(" idToken : " + idToken);

	if (idToken == null) {
		log.error("Failed to get id_token");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	log.info("Session validation successful. User is logged in");
	UserInfoClient userInfoClient = new UserInfoClient(openIdConfiguration.getUserInfoEndpoint());
	UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);
	if (userInfoResponse == null) {
		log.error("Get empty token response. User can't log into application");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Parse JWT
	Jwt jwt;
	try {
		jwt = Jwt.parse(idToken);
	} catch (InvalidJwtException ex) {
		log.error("Failed to parse id_token");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Check nonce
	String nonceResponse = (String) jwt.getClaims().getClaim(JwtClaimName.NONCE);
	String nonceSession = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_NONCE);
	if (!StringHelper.equals(nonceSession, nonceResponse)) {
		log.error("User info response :  nonce is not matching.");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Determine uid
	List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME);
	if ((uidValues == null) || (uidValues.size() == 0)) {
		log.error("User info response doesn't contains uid claim");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}
	// Check requested authentication method
	if (identity.getSessionMap().containsKey(OxTrustConstants.OXAUTH_ACR_VALUES)) {
		String requestAcrValues = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_ACR_VALUES);
		String issuer = openIdConfiguration.getIssuer();
		String responseIssuer = (String) jwt.getClaims().getClaim(JwtClaimName.ISSUER);
		if (issuer == null || responseIssuer == null || !issuer.equals(responseIssuer)) {
			log.error("User info response :  Issuer.");
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}

		List<String> acrValues = jwt.getClaims()
				.getClaimAsStringList(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE);
		if ((acrValues == null) || (acrValues.size() == 0) || !acrValues.contains(requestAcrValues)) {
			log.error("User info response doesn't contains acr claim");
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}
		if (!acrValues.contains(requestAcrValues)) {
			log.error("User info response contains acr='{}' claim but expected acr='{}'", acrValues,
					requestAcrValues);
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}
	}
	OauthData oauthData = identity.getOauthData();
	oauthData.setHost(oxAuthHost);
	oauthData.setUserUid(uidValues.get(0));
	oauthData.setAccessToken(accessToken);
	oauthData.setAccessTokenExpirationInSeconds(tokenResponse.getExpiresIn());
	oauthData.setScopes(scopes);
	oauthData.setIdToken(idToken);
	oauthData.setSessionState(sessionState);
	identity.setWorkingParameter(OxTrustConstants.OXAUTH_SSO_SESSION_STATE, Boolean.FALSE);
	log.info("user uid:" + oauthData.getUserUid());

	String result = authenticate();

	return result;
}
 
Example #14
Source File: GetTokensByCodeOperation.java    From oxd with Apache License 2.0 4 votes vote down vote up
@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());
    tokenRequest.setAuthPassword(rp.getClientSecret());
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);


    final TokenClient tokenClient = getOpClientFactory().createTokenClient(discoveryResponse.getTokenEndpoint());
    tokenClient.setExecutor(getHttpService().getClientExecutor());
    tokenClient.setRequest(tokenRequest);
    final TokenResponse response = tokenClient.exec();

    if (response.getStatus() == 200 || response.getStatus() == 302) { // success or redirect

        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())
                .oxdServerConfiguration(getConfigurationService().getConfiguration())
                .rp(rp)
                .build();

        validator.validateNonce(getStateService());
        validator.validateIdToken();
        validator.validateAccessToken(response.getAccessToken());

        // persist tokens
        rp.setIdToken(response.getIdToken());
        rp.setAccessToken(response.getAccessToken());
        getRpService().update(rp);
        getStateService().deleteExpiredObjectsByKey(params.getState());

        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;
}
 
Example #15
Source File: DiscoveryService.java    From oxd with Apache License 2.0 4 votes vote down vote up
public OpenIdConfigurationResponse getConnectDiscoveryResponseByOxdId(String oxdId) {
    validationService.notBlankOxdId(oxdId);

    Rp rp = rpSyncService.getRp(oxdId);
    return getConnectDiscoveryResponse(rp);
}
 
Example #16
Source File: DiscoveryService.java    From oxd with Apache License 2.0 4 votes vote down vote up
public OpenIdConfigurationResponse getConnectDiscoveryResponse(Rp rp) {
    return getConnectDiscoveryResponse(rp.getOpConfigurationEndpoint(), rp.getOpHost(), rp.getOpDiscoveryPath());
}
 
Example #17
Source File: DiscoveryService.java    From oxd with Apache License 2.0 4 votes vote down vote up
public OpenIdConfigurationResponse getConnectDiscoveryResponse(String opConfigurationEndpoint, String opHost, String opDiscoveryPath) {
    return Strings.isNullOrEmpty(opConfigurationEndpoint) ? getConnectDiscoveryResponse(getConnectDiscoveryUrl(opHost, opDiscoveryPath))
            : getConnectDiscoveryResponse(opConfigurationEndpoint);
}
 
Example #18
Source File: OpenIdService.java    From oxTrust with MIT License 4 votes vote down vote up
public OpenIdConfigurationResponse getOpenIdConfiguration() {
    // Call each time to allows retry
    init();

    return openIdConfiguration;
}