Search in sources :

Example 61 with AccessToken

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

the class CompositeRoleTest method testRealmOnlyWithUserCompositeAppComposite.

@Test
public void testRealmOnlyWithUserCompositeAppComposite() throws Exception {
    oauth.realm("test");
    oauth.clientId("REALM_COMPOSITE_1_APPLICATION");
    oauth.doLogin("REALM_COMPOSITE_1_USER", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    Assert.assertEquals(200, response.getStatusCode());
    Assert.assertEquals("Bearer", response.getTokenType());
    AccessToken token = oauth.verifyToken(response.getAccessToken());
    Assert.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject());
    Assert.assertEquals(2, token.getRealmAccess().getRoles().size());
    Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_COMPOSITE_1"));
    Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1"));
    AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(response.getRefreshToken(), "password");
    Assert.assertEquals(200, refreshResponse.getStatusCode());
}
Also used : AccessToken(org.keycloak.representations.AccessToken) AccessTokenResponse(org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse) Test(org.junit.Test)

Example 62 with AccessToken

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

the class ParTest method testSuccessfulMultipleParBySameClient.

// success with the same client conducting multiple authz requests + PAR simultaneously
@Test
public void testSuccessfulMultipleParBySameClient() throws Exception {
    // create client dynamically
    String clientId = createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
        clientRep.setRequirePushedAuthorizationRequests(Boolean.FALSE);
        clientRep.setRedirectUris(new ArrayList<String>(Arrays.asList(CLIENT_REDIRECT_URI)));
    });
    OIDCClientRepresentation oidcCRep = getClientDynamically(clientId);
    String clientSecret = oidcCRep.getClientSecret();
    assertEquals(Boolean.FALSE, oidcCRep.getRequirePushedAuthorizationRequests());
    assertTrue(oidcCRep.getRedirectUris().contains(CLIENT_REDIRECT_URI));
    assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, oidcCRep.getTokenEndpointAuthMethod());
    // Pushed Authorization Request #1
    oauth.clientId(clientId);
    oauth.redirectUri(CLIENT_REDIRECT_URI);
    ParResponse pResp = oauth.doPushedAuthorizationRequest(clientId, clientSecret);
    assertEquals(201, pResp.getStatusCode());
    String requestUriOne = pResp.getRequestUri();
    // Pushed Authorization Request #2
    oauth.clientId(clientId);
    oauth.scope("microprofile-jwt" + " " + "profile");
    oauth.redirectUri(CLIENT_REDIRECT_URI);
    pResp = oauth.doPushedAuthorizationRequest(clientId, clientSecret);
    assertEquals(201, pResp.getStatusCode());
    String requestUriTwo = pResp.getRequestUri();
    // Authorization Request with request_uri of PAR #2
    // remove parameters as query strings of uri
    oauth.redirectUri(null);
    oauth.scope(null);
    oauth.responseType(null);
    oauth.requestUri(requestUriTwo);
    String state = oauth.stateParamRandom().getState();
    oauth.stateParamHardcoded(state);
    OAuthClient.AuthorizationEndpointResponse loginResponse = oauth.doLogin(TEST_USER2_NAME, TEST_USER2_PASSWORD);
    assertEquals(state, loginResponse.getState());
    String code = loginResponse.getCode();
    String sessionId = loginResponse.getSessionState();
    // Token Request #2
    // get tokens, it needed. https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
    oauth.redirectUri(CLIENT_REDIRECT_URI);
    OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    AccessToken token = oauth.verifyToken(res.getAccessToken());
    String userId = findUserByUsername(adminClient.realm(REALM_NAME), TEST_USER2_NAME).getId();
    assertEquals(userId, token.getSubject());
    assertEquals(sessionId, token.getSessionState());
    Assert.assertNotEquals(TEST_USER2_NAME, token.getSubject());
    assertEquals(clientId, token.getIssuedFor());
    assertTrue(token.getScope().contains("openid"));
    assertTrue(token.getScope().contains("microprofile-jwt"));
    assertTrue(token.getScope().contains("profile"));
    // Logout
    // same oauth instance is used so that this logout is needed to send authz request consecutively.
    oauth.doLogout(res.getRefreshToken(), clientSecret);
    // Authorization Request with request_uri of PAR #1
    // remove parameters as query strings of uri
    oauth.redirectUri(null);
    oauth.scope(null);
    oauth.responseType(null);
    oauth.requestUri(requestUriOne);
    state = oauth.stateParamRandom().getState();
    oauth.stateParamHardcoded(state);
    loginResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    assertEquals(state, loginResponse.getState());
    code = loginResponse.getCode();
    sessionId = loginResponse.getSessionState();
    // Token Request #1
    // get tokens, it needed. https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
    oauth.redirectUri(CLIENT_REDIRECT_URI);
    res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    token = oauth.verifyToken(res.getAccessToken());
    userId = findUserByUsername(adminClient.realm(REALM_NAME), TEST_USER_NAME).getId();
    assertEquals(userId, token.getSubject());
    assertEquals(sessionId, token.getSessionState());
    Assert.assertNotEquals(TEST_USER_NAME, token.getSubject());
    assertEquals(clientId, token.getIssuedFor());
    assertFalse(token.getScope().contains("microprofile-jwt"));
    assertTrue(token.getScope().contains("openid"));
}
Also used : ParResponse(org.keycloak.testsuite.util.OAuthClient.ParResponse) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) AbstractClientPoliciesTest(org.keycloak.testsuite.client.AbstractClientPoliciesTest) Test(org.junit.Test)

Example 63 with AccessToken

use of org.keycloak.representations.AccessToken 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 64 with AccessToken

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

the class AbstractOIDCScopeTest method sendTokenRequest.

protected AbstractOIDCScopeTest.Tokens sendTokenRequest(EventRepresentation loginEvent, String userId, String expectedScope, String clientId) {
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    Assert.assertEquals(200, response.getStatusCode());
    // Test scopes
    log.info("expectedScopes = " + expectedScope);
    log.info("responseScopes = " + response.getScope());
    assertScopes(expectedScope, response.getScope());
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());
    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    // Test scope in the access token
    assertScopes(expectedScope, accessToken.getScope());
    EventRepresentation codeToTokenEvent = events.expectCodeToToken(codeId, sessionId).user(userId).client(clientId).assertEvent();
    // Test scope in the event
    assertScopes(expectedScope, codeToTokenEvent.getDetails().get(Details.SCOPE));
    return new AbstractOIDCScopeTest.Tokens(idToken, accessToken, response.getRefreshToken());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) IDToken(org.keycloak.representations.IDToken)

Example 65 with AccessToken

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

the class AuthorizationTokenResponseModeTest method authorizationRequestJWTResponseModeAccessTokenResponseType.

@Test
public void authorizationRequestJWTResponseModeAccessTokenResponseType() throws Exception {
    ClientManager.realm(adminClient.realm("test")).clientId("test-app").implicitFlow(true);
    // jwt response_mode. It should fallback to fragment.jwt when its hybrid flow
    oauth.responseMode("jwt");
    oauth.responseType("token id_token");
    oauth.stateParamHardcoded("OpenIdConnect.AuthenticationProperties=2302984sdlk");
    oauth.nonce("123456");
    OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
    assertTrue(response.isRedirected());
    AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse());
    assertEquals("test-app", responseToken.getAudience()[0]);
    Assert.assertNull(responseToken.getOtherClaims().get("code"));
    assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state"));
    Assert.assertNull(responseToken.getOtherClaims().get("error"));
    Assert.assertNotNull(responseToken.getOtherClaims().get("id_token"));
    String idTokenEncoded = (String) responseToken.getOtherClaims().get("id_token");
    IDToken idToken = oauth.verifyIDToken(idTokenEncoded);
    assertEquals("123456", idToken.getNonce());
    Assert.assertNotNull(responseToken.getOtherClaims().get("access_token"));
    String accessTokenEncoded = (String) responseToken.getOtherClaims().get("access_token");
    AccessToken accessToken = oauth.verifyToken(accessTokenEncoded);
    assertEquals("123456", accessToken.getNonce());
    URI currentUri = new URI(driver.getCurrentUrl());
    Assert.assertNull(currentUri.getRawQuery());
    Assert.assertNotNull(currentUri.getRawFragment());
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) IDToken(org.keycloak.representations.IDToken) URI(java.net.URI) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

AccessToken (org.keycloak.representations.AccessToken)230 Test (org.junit.Test)129 OAuthClient (org.keycloak.testsuite.util.OAuthClient)104 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)54 RefreshToken (org.keycloak.representations.RefreshToken)45 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)37 JWSInput (org.keycloak.jose.jws.JWSInput)29 Permission (org.keycloak.representations.idm.authorization.Permission)28 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)27 Response (javax.ws.rs.core.Response)26 ClientResource (org.keycloak.admin.client.resource.ClientResource)22 VerificationException (org.keycloak.common.VerificationException)19 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)19 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)18 IDToken (org.keycloak.representations.IDToken)18 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)17 IOException (java.io.IOException)15 AuthzClient (org.keycloak.authorization.client.AuthzClient)15 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)14 ArrayList (java.util.ArrayList)13