Search in sources :

Example 11 with AccessTokenResponse

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

the class UserInfoTest method testSuccess_dotsInClientId.

// KEYCLOAK-8838
@Test
public void testSuccess_dotsInClientId() throws Exception {
    // Create client with dot in the name
    ClientRepresentation clientRep = org.keycloak.testsuite.util.ClientBuilder.create().clientId("my.foo.client").addRedirectUri("http://foo.host").secret("password").directAccessGrants().build();
    RealmResource realm = adminClient.realm("test");
    Response resp = realm.clients().create(clientRep);
    String clientUUID = ApiUtil.getCreatedId(resp);
    resp.close();
    getCleanup().addClientUuid(clientUUID);
    // Create role with dot in the name
    realm.clients().get(clientUUID).roles().create(RoleBuilder.create().name("my.foo.role").build());
    // Assign role to the user
    RoleRepresentation fooRole = realm.clients().get(clientUUID).roles().get("my.foo.role").toRepresentation();
    UserResource userResource = ApiUtil.findUserByUsernameId(realm, "test-user@localhost");
    userResource.roles().clientLevel(clientUUID).add(Collections.singletonList(fooRole));
    // Login to the new client
    OAuthClient.AccessTokenResponse accessTokenResponse = oauth.clientId("my.foo.client").doGrantAccessTokenRequest("password", "test-user@localhost", "password");
    AccessToken accessToken = oauth.verifyToken(accessTokenResponse.getAccessToken());
    Assert.assertNames(accessToken.getResourceAccess("my.foo.client").getRoles(), "my.foo.role");
    events.clear();
    // Send UserInfo request and ensure it is correct
    Client client = AdminClientUtil.createResteasyClient();
    try {
        Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getAccessToken());
        testSuccessfulUserInfoResponse(response, "my.foo.client");
    } finally {
        client.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) AccessToken(org.keycloak.representations.AccessToken) UserResource(org.keycloak.admin.client.resource.UserResource) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 12 with AccessTokenResponse

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

the class UserInfoTest method testAccessTokenExpired.

@Test
public void testAccessTokenExpired() {
    Client client = AdminClientUtil.createResteasyClient();
    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);
        setTimeOffset(600);
        Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());
        assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
        String wwwAuthHeader = response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE);
        assertNotNull(wwwAuthHeader);
        assertThat(wwwAuthHeader, CoreMatchers.containsString("Bearer"));
        assertThat(wwwAuthHeader, CoreMatchers.containsString("error=\"" + OAuthErrorException.INVALID_TOKEN + "\""));
        response.close();
        events.expect(EventType.USER_INFO_REQUEST_ERROR).error(Errors.INVALID_TOKEN).user(Matchers.nullValue(String.class)).session(Matchers.nullValue(String.class)).detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN).client((String) null).assertEvent();
    } finally {
        client.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 13 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 14 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 15 with AccessTokenResponse

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

the class TokenEndpoint method createTokenResponse.

public Response createTokenResponse(UserModel user, UserSessionModel userSession, ClientSessionContext clientSessionCtx, String scopeParam, boolean code) {
    AccessToken token = tokenManager.createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);
    TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).accessToken(token);
    if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
        responseBuilder.generateRefreshToken();
    }
    checkMtlsHoKToken(responseBuilder, OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken());
    if (TokenUtil.isOIDCRequest(scopeParam)) {
        responseBuilder.generateIDToken().generateAccessTokenHash();
    }
    AccessTokenResponse res = null;
    if (code) {
        try {
            res = responseBuilder.build();
        } catch (RuntimeException re) {
            if ("can not get encryption KEK".equals(re.getMessage())) {
                throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "can not get encryption KEK", Response.Status.BAD_REQUEST);
            } else {
                throw re;
            }
        }
    } else {
        res = responseBuilder.build();
    }
    event.success();
    return cors.builder(Response.ok(res).type(MediaType.APPLICATION_JSON_TYPE)).build();
}
Also used : AccessToken(org.keycloak.representations.AccessToken) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) TokenManager(org.keycloak.protocol.oidc.TokenManager) 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