Search in sources :

Example 1 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 2 with AccessTokenResponse

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

the class BasicAuthRequestAuthenticator method authenticate.

public AuthOutcome authenticate(HttpFacade exchange) {
    List<String> authHeaders = exchange.getRequest().getHeaders("Authorization");
    if (authHeaders == null || authHeaders.isEmpty()) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.NO_AUTHORIZATION_HEADER, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }
    tokenString = null;
    for (String authHeader : authHeaders) {
        String[] split = authHeader.trim().split("\\s+");
        if (split.length != 2)
            continue;
        if (!split[0].equalsIgnoreCase("Basic"))
            continue;
        tokenString = split[1];
    }
    if (tokenString == null) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }
    AccessTokenResponse atr = null;
    try {
        String userpw = new String(Base64.decode(tokenString));
        int seperatorIndex = userpw.indexOf(":");
        String user = userpw.substring(0, seperatorIndex);
        String pw = userpw.substring(seperatorIndex + 1);
        atr = getToken(user, pw);
        tokenString = atr.getToken();
    } catch (Exception e) {
        log.debug("Failed to obtain token", e);
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, "no_token", e.getMessage());
        return AuthOutcome.FAILED;
    }
    return authenticateToken(exchange, atr.getToken());
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 3 with AccessTokenResponse

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

the class KeycloakInstalled method processCode.

private void processCode(String code, String redirectUri, Pkce pkce) throws IOException, ServerRequest.HttpFailure, VerificationException {
    AccessTokenResponse tokenResponse = ServerRequest.invokeAccessCodeToToken(deployment, code, redirectUri, null, pkce == null ? null : pkce.getCodeVerifier());
    parseAccessToken(tokenResponse);
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 4 with AccessTokenResponse

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

the class ConfigCredentialsCmd method process.

public CommandResult process(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    // check server
    if (server == null) {
        throw new IllegalArgumentException("Required option not specified: --server");
    }
    try {
        new URL(server);
    } catch (Exception e) {
        throw new RuntimeException("Invalid server endpoint url: " + server, e);
    }
    if (realm == null)
        throw new IllegalArgumentException("Required option not specified: --realm");
    String signedRequestToken = null;
    boolean clientSet = clientId != null;
    applyDefaultOptionValues();
    String grantTypeForAuthentication = null;
    if (user != null) {
        grantTypeForAuthentication = OAuth2Constants.PASSWORD;
        printErr("Logging into " + server + " as user " + user + " of realm " + realm);
        // if user was set there needs to be a password so we can authenticate
        if (password == null) {
            password = readSecret("Enter password: ", commandInvocation);
        }
        // if secret was set to be read from stdin, then ask for it
        if ("-".equals(secret) && keystore == null) {
            secret = readSecret("Enter client secret: ", commandInvocation);
        }
    } else if (keystore != null || secret != null || clientSet) {
        grantTypeForAuthentication = OAuth2Constants.CLIENT_CREDENTIALS;
        printErr("Logging into " + server + " as " + "service-account-" + clientId + " of realm " + realm);
        if (keystore == null) {
            if (secret == null) {
                secret = readSecret("Enter client secret: ", commandInvocation);
            }
        }
    }
    if (keystore != null) {
        if (secret != null) {
            throw new IllegalArgumentException("Can't use both --keystore and --secret");
        }
        if (!new File(keystore).isFile()) {
            throw new RuntimeException("No such keystore file: " + keystore);
        }
        if (storePass == null) {
            storePass = readSecret("Enter keystore password: ", commandInvocation);
            keyPass = readSecret("Enter key password: ", commandInvocation);
        }
        if (keyPass == null) {
            keyPass = storePass;
        }
        if (alias == null) {
            alias = clientId;
        }
        String realmInfoUrl = server + "/realms/" + realm;
        signedRequestToken = AuthUtil.getSignedRequestToken(keystore, storePass, keyPass, alias, sigLifetime, clientId, realmInfoUrl);
    }
    // if only server and realm are set, just save config and be done
    if (user == null && secret == null && keystore == null) {
        getHandler().saveMergeConfig(config -> {
            config.setServerUrl(server);
            config.setRealm(realm);
        });
        return CommandResult.SUCCESS;
    }
    setupTruststore(copyWithServerInfo(loadConfig()), commandInvocation);
    // now use the token endpoint to retrieve access token, and refresh token
    AccessTokenResponse tokens = signedRequestToken != null ? getAuthTokensByJWT(server, realm, user, password, clientId, signedRequestToken) : secret != null ? getAuthTokensBySecret(server, realm, user, password, clientId, secret) : getAuthTokens(server, realm, user, password, clientId);
    Long sigExpiresAt = signedRequestToken == null ? null : System.currentTimeMillis() + sigLifetime * 1000;
    // save tokens to config file
    saveTokens(tokens, server, realm, clientId, signedRequestToken, sigExpiresAt, secret, grantTypeForAuthentication);
    return CommandResult.SUCCESS;
}
Also used : File(java.io.File) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) URL(java.net.URL) CommandException(org.jboss.aesh.console.command.CommandException)

Example 5 with AccessTokenResponse

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

the class AdminConsolePermissionsCalculatedTest method changeRealmTokenAlgorithm.

@Test
public void changeRealmTokenAlgorithm() throws Exception {
    try (Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString());
        Creator c = Creator.create(adminClient, RealmBuilder.create().name(REALM_NAME).build())) {
        AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken();
        assertNotNull(adminClient.realms().findAll());
        String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami";
        JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson();
        assertTrue("Permissions for " + Config.getAdminRealm() + " realm.", jsonNode.at("/realm_access/" + Config.getAdminRealm()).isArray());
        assertTrue("Permissions for " + REALM_NAME + " realm.", jsonNode.at("/realm_access/" + REALM_NAME).isArray());
    }
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) Creator(org.keycloak.testsuite.updaters.Creator) Keycloak(org.keycloak.admin.client.Keycloak) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Aggregations

AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)73 Response (javax.ws.rs.core.Response)30 Test (org.junit.Test)29 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