Search in sources :

Example 26 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class UmaGrantTypeTest method testNoRefreshToken.

@Test
public void testNoRefreshToken() {
    ClientResource client = getClient(getRealm());
    ClientRepresentation clientRepresentation = client.toRepresentation();
    clientRepresentation.getAttributes().put(OIDCConfigAttributes.USE_REFRESH_TOKEN, "false");
    client.update(clientRepresentation);
    AccessTokenResponse accessTokenResponse = getAuthzClient().obtainAccessToken("marta", "password");
    AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB"));
    String rpt = response.getToken();
    String refreshToken = response.getRefreshToken();
    assertNotNull(rpt);
    assertNull(refreshToken);
    clientRepresentation.getAttributes().put(OIDCConfigAttributes.USE_REFRESH_TOKEN, "true");
    client.update(clientRepresentation);
}
Also used : PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) ClientResource(org.keycloak.admin.client.resource.ClientResource) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Example 27 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class AccountLinkSpringBootTest method getToken.

private String getToken(OAuthClient.AccessTokenResponse response, Client httpClient) throws Exception {
    log.info("target here is " + OAuthClient.AUTH_SERVER_ROOT);
    String idpToken = httpClient.target(OAuthClient.AUTH_SERVER_ROOT).path("realms").path(REALM_NAME).path("broker").path(PARENT_REALM).path("token").request().header("Authorization", "Bearer " + response.getAccessToken()).get(String.class);
    AccessTokenResponse res = JsonSerialization.readValue(idpToken, AccessTokenResponse.class);
    return res.getToken();
}
Also used : CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 28 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project indy by Commonjava.

the class BasicAuthenticationOAuthTranslator method lookupToken.

private AccessTokenResponse lookupToken(final UserPass userPass) {
    final URI uri = KeycloakUriBuilder.fromUri(config.getUrl()).path(ServiceUrlConstants.TOKEN_PATH).build(config.getRealm());
    logger.debug("Looking up token at: {}", uri);
    final HttpPost request = new HttpPost(uri);
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(USERNAME, userPass.getUser()));
    params.add(new BasicNameValuePair(PASSWORD, userPass.getPassword()));
    params.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
    final String authorization = BasicAuthHelper.createHeader(config.getServerResource(), config.getServerCredentialSecret());
    request.setHeader(AUTHORIZATION_HEADER, authorization);
    CloseableHttpClient client = null;
    AccessTokenResponse tokenResponse = null;
    try {
        client = http.createClient(uri.getHost());
        final UrlEncodedFormEntity form = new UrlEncodedFormEntity(params, "UTF-8");
        request.setEntity(form);
        CloseableHttpResponse response = client.execute(request);
        logger.debug("Got response status: {}", response.getStatusLine());
        if (response.getStatusLine().getStatusCode() == 200) {
            try (InputStream in = response.getEntity().getContent()) {
                final String json = IOUtils.toString(in);
                logger.debug("Token response:\n\n{}\n\n", json);
                tokenResponse = JsonSerialization.readValue(json, AccessTokenResponse.class);
            }
        }
    } catch (IOException | IndyHttpException e) {
        logger.error(String.format("Keycloak token request failed: %s", e.getMessage()), e);
    } finally {
        IOUtils.closeQuietly(client);
    }
    return tokenResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IndyHttpException(org.commonjava.indy.subsys.http.IndyHttpException) HttpString(io.undertow.util.HttpString) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URI(java.net.URI) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 29 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project alfresco-repository by Alfresco.

the class IdentityServiceAuthenticationComponentTest method testAuthenticationPass.

@Test
public void testAuthenticationPass() {
    when(mockAuthzClient.obtainAccessToken("username", "password")).thenReturn(new AccessTokenResponse());
    authComponent.authenticateImpl("username", "password".toCharArray());
    // Check that the authenticated user has been set
    assertEquals("User has not been set as expected.", "username", authenticationContext.getCurrentUserName());
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) BaseSpringTest(org.alfresco.util.BaseSpringTest) Test(org.junit.Test)

Example 30 with AccessTokenResponse

use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.

the class DirectAccessGrantsLoginModule method directGrantAuth.

protected Auth directGrantAuth(String username, String password) throws IOException, VerificationException {
    String authServerBaseUrl = deployment.getAuthServerBaseUrl();
    HttpPost post = new HttpPost(deployment.getTokenUrl());
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
    formparams.add(new BasicNameValuePair("username", username));
    formparams.add(new BasicNameValuePair("password", password));
    if (scope != null) {
        formparams.add(new BasicNameValuePair(OAuth2Constants.SCOPE, scope));
    }
    ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);
    UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
    post.setEntity(form);
    HttpClient client = deployment.getClient();
    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    if (status != 200) {
        StringBuilder errorBuilder = new StringBuilder("Login failed. Invalid status: " + status);
        if (entity != null) {
            InputStream is = entity.getContent();
            OAuth2ErrorRepresentation errorRep = JsonSerialization.readValue(is, OAuth2ErrorRepresentation.class);
            errorBuilder.append(", OAuth2 error. Error: " + errorRep.getError()).append(", Error description: " + errorRep.getErrorDescription());
        }
        String error = errorBuilder.toString();
        log.warn(error);
        throw new IOException(error);
    }
    if (entity == null) {
        throw new IOException("No Entity");
    }
    InputStream is = entity.getContent();
    AccessTokenResponse tokenResponse = JsonSerialization.readValue(is, AccessTokenResponse.class);
    // refreshToken will be saved to privateCreds of Subject for now
    refreshToken = tokenResponse.getRefreshToken();
    AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenResponse.getToken(), tokenResponse.getIdToken(), deployment);
    return postTokenVerification(tokenResponse.getToken(), tokens.getAccessToken());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) AdapterTokenVerifier(org.keycloak.adapters.rotation.AdapterTokenVerifier) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpClient(org.apache.http.client.HttpClient) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Aggregations

AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)74 Response (javax.ws.rs.core.Response)30 Test (org.junit.Test)30 OAuthClient (org.keycloak.testsuite.util.OAuthClient)25 Client (javax.ws.rs.client.Client)24 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)17 Form (javax.ws.rs.core.Form)15 WebTarget (javax.ws.rs.client.WebTarget)14 AccessToken (org.keycloak.representations.AccessToken)14 IOException (java.io.IOException)12 ClientResource (org.keycloak.admin.client.resource.ClientResource)7 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)7 AuthzClient (org.keycloak.authorization.client.AuthzClient)5 PermissionRequest (org.keycloak.representations.idm.authorization.PermissionRequest)5 CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)5 UncaughtServerErrorExpected (org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)5 InputStream (java.io.InputStream)4 URI (java.net.URI)4 NameValuePair (org.apache.http.NameValuePair)4 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)4