Java Code Examples for org.gluu.oxauth.client.TokenClient#setRequest()

The following examples show how to use org.gluu.oxauth.client.TokenClient#setRequest() . 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: 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 2
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 3
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 4
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 5
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;
}