org.gluu.oxauth.client.TokenClient Java Examples

The following examples show how to use org.gluu.oxauth.client.TokenClient. 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: ObtainPatTokenFlowHttpTest.java    From oxAuth with MIT License 6 votes vote down vote up
/**
 * Test for the obtaining UMA PAT token using refresh token
 */
//@Test(dependsOnMethods = {"testObtainPatTokenFlow"})
@Parameters({"umaPatClientId", "umaPatClientSecret"})
public void testObtainPatTokenUsingRefreshTokenFlow(final String umaPatClientId, final String umaPatClientSecret) throws Exception {
    showTitle("testObtainPatTokenUsingRefreshTokenFlow");

    // Request new access token using the refresh token.
    TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    TokenResponse response1 = tokenClient1.execRefreshToken(m_pat.getScope(), m_pat.getRefreshToken(), umaPatClientId, umaPatClientSecret);

    showClient(tokenClient1);
    assertEquals(response1.getStatus(), 200, "Unexpected response code: " + response1.getStatus());
    assertNotNull(response1.getEntity(), "The entity is null");
    assertNotNull(response1.getAccessToken(), "The access token is null");
    assertNotNull(response1.getTokenType(), "The token type is null");
    assertNotNull(response1.getRefreshToken(), "The refresh token is null");
    assertNotNull(response1.getScope(), "The scope is null");
}
 
Example #2
Source File: TokenAction.java    From oxAuth with MIT License 5 votes vote down vote up
public void exec() {
    try {
        TokenRequest request = new TokenRequest(grantType);
        request.setAuthUsername(clientId);
        request.setAuthPassword(clientSecret);
        request.setCode(code);
        request.setRedirectUri(redirectUri);
        request.setUsername(username);
        request.setPassword(password);
        request.setScope(scope);
        request.setAssertion(assertion);
        request.setRefreshToken(refreshToken);
        request.setAuthenticationMethod(authenticationMethod);
        if (authenticationMethod.equals(AuthenticationMethod.CLIENT_SECRET_JWT)) {
            request.setAudience(tokenEndpoint);
        }
        request.setAuthReqId(authReqId);

        TokenClient client = new TokenClient(tokenEndpoint);
        client.setRequest(request);
        TokenResponse response = client.exec();

        if (response.getStatus() == 200) {
            userInfoAction.setAccessToken(response.getAccessToken());
        }

        showResults = true;
        requestString = client.getRequestAsString();
        responseString = client.getResponseAsString();
    } catch (Exception e) {
    	log.error(e.getMessage(), e);
    }
}
 
Example #3
Source File: ClientCredentialsTest.java    From oxd with Apache License 2.0 5 votes vote down vote up
@Parameters({"clientId", "clientSecret"})
@Test(enabled = false) // for manual run
public void test(String clientId, String clientSecret) {
    final String tokenEndpoint = "https://ce-dev.gluu.org/oxauth/seam/resource/restv1/oxauth/token";
    final TokenClient tokenClient = new TokenClient(tokenEndpoint);
    final TokenResponse response = tokenClient.execClientCredentialsGrant("openid", clientId, clientSecret);
    System.out.println(response);
}
 
Example #4
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 #5
Source File: MTSLClientAuthenticationTest.java    From oxAuth with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        File jdkJks = new File("u:\\tmp\\ce-ob\\clientkeystore");
        if (!jdkJks.exists()) {
            throw new RuntimeException("Failed to find jks trust store");
        }

        File certificate = new File("u:\\tmp\\ce-ob\\fullchain.p12");
        if (!certificate.exists()) {
            throw new RuntimeException("Failed to find certificate");
        }

        HttpClient httpclient = new DefaultHttpClient();
// truststore
        KeyStore ts = KeyStore.getInstance("JKS", "SUN");
        ts.load(new FileInputStream(jdkJks), "secret".toCharArray());
// if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing truststore
        if(0 == ts.size()) throw new IOException("Error loading truststore");
// tmf
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);
// keystore
        KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
        ks.load(new FileInputStream(certificate), "".toCharArray());
// if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing keystore
        if(0 == ks.size()) throw new IOException("Error loading keystore");
// kmf
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "".toCharArray());
// SSL
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// socket
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        String clientId = "@!D445.22BF.5EF1.0D87!0001!03F2.297D!0008!F599.E2C7";
        String clientSecret = "testClientSecret";

        TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
        tokenRequest.setCode("testCode");
        tokenRequest.setRedirectUri("https://ce-ob.gluu.org/cas/login");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.TLS_CLIENT_AUTH);

        TokenClient tokenClient = new TokenClient("https://ce-ob.gluu.org/oxauth/restv1/token");
        tokenClient.setExecutor(new ApacheHttpClient4Executor(httpclient));
        tokenClient.setRequest(tokenRequest);
        TokenResponse tokenResponse = tokenClient.exec();

        System.out.println(tokenResponse);
        showClient(tokenClient);
    }
 
Example #6
Source File: ClientAuthenticationByAccessTokenHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret"})
@Test(dependsOnMethods = "requestClientRegistrationWithCustomAttributes")
public void requestAccessTokenCustomClientAuth1(final String userId, final String userSecret) throws Exception {
    showTitle("requestAccessTokenCustomClientAuth1");

    // 1. Request authorization and receive the authorization code.
    List<ResponseType> responseTypes = Arrays.asList(
            ResponseType.CODE,
            ResponseType.ID_TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");

    String state = UUID.randomUUID().toString();
    String nonce = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, REDIRECT_URI, nonce);
    authorizationRequest.setState(state);
    authorizationRequest.setAuthUsername(userId);
    authorizationRequest.setAuthPassword(userSecret);
    authorizationRequest.getPrompts().add(Prompt.NONE);

    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setExecutor(clientExecutor(true));
    authorizeClient.setRequest(authorizationRequest);
    AuthorizationResponse authorizationResponse = authorizeClient.exec();

    showClient(authorizeClient);
    assertEquals(authorizationResponse.getStatus(), 302, "Unexpected response code: " + authorizationResponse.getStatus());
    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getCode(), "The code is null");
    assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");

    String authorizationCode = authorizationResponse.getCode();
    String idToken = authorizationResponse.getIdToken();

    // 2. Validate code and id_token
    Jwt jwt = Jwt.parse(idToken);
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));

    // 3. Request access token using the authorization code.
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(REDIRECT_URI);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setExecutor(clientExecutor(true));
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");

    userAccessToken = tokenResponse.getAccessToken();
}
 
Example #7
Source File: ObtainAccessTokenLoadTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris"})
@Test(invocationCount = 1000, threadPoolSize = 100)
public void obtainAccessToken(final String userId, final String userSecret, String redirectUris) throws Exception {
    showTitle("requestClientAssociate1");

    redirectUris = "https://client.example.com/cb";

    final List<ResponseType> responseTypes = new ArrayList<ResponseType>();
    responseTypes.add(ResponseType.CODE);
    responseTypes.add(ResponseType.ID_TOKEN);

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                    StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse response = registerClient.exec();

    showClient(registerClient);
    assertEquals(response.getStatus(), 200, "Unexpected response code: " + response.getEntity());
    assertNotNull(response.getClientId());
    assertNotNull(response.getClientSecret());
    assertNotNull(response.getRegistrationAccessToken());
    assertNotNull(response.getClientSecretExpiresAt());

    final String clientId = response.getClientId();
    final String clientSecret = response.getClientSecret();

    // 1. Request authorization and receive the authorization code.

    final List<String> scopes = Arrays.asList("openid", "profile", "address", "email");

    final AuthorizationRequest request = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUris, null);
    request.setState("af0ifjsldkj");
    request.setAuthUsername(userId);
    request.setAuthPassword(userSecret);
    request.getPrompts().add(Prompt.NONE);

    final AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(request);
    final AuthorizationResponse response1 = authorizeClient.exec();

    ClientUtils.showClient(authorizeClient);

    final String scope = response1.getScope();
    final String authorizationCode = response1.getCode();
    assertTrue(Util.allNotBlank(authorizationCode));


    // 2. Request access token using the authorization code.
    final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUris);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    tokenRequest.setScope(scope);

    final TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    tokenClient1.setRequest(tokenRequest);
    final TokenResponse response2 = tokenClient1.exec();
    ClientUtils.showClient(authorizeClient);

    assertTrue(response2.getStatus() == 200);
    final String patToken = response2.getAccessToken();
    final String patRefreshToken = response2.getRefreshToken();
    assertTrue(Util.allNotBlank(patToken, patRefreshToken));
}
 
Example #8
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;
}