Search in sources :

Example 16 with AccessToken

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

the class CIBATest method testClientScopesCondition.

@Test
public void testClientScopesCondition() throws Exception {
    String username = "nutzername-rot";
    String bindingMessage = "ThisIsBindingMessage";
    Map<String, String> additionalParameters = new HashMap<>();
    additionalParameters.put("user_device", "mobile");
    String clientConfidentialId = generateSuffixedName("confidential-app");
    String clientConfidentialSecret = "app-secret";
    String cidConfidential = createClientByAdmin(clientConfidentialId, (ClientRepresentation clientRep) -> {
        clientRep.setSecret(clientConfidentialSecret);
        clientRep.setStandardFlowEnabled(Boolean.TRUE);
        clientRep.setImplicitFlowEnabled(Boolean.TRUE);
        clientRep.setPublicClient(Boolean.FALSE);
        clientRep.setBearerOnly(Boolean.FALSE);
        Map<String, String> attributes = Optional.ofNullable(clientRep.getAttributes()).orElse(new HashMap<>());
        attributes.put(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT, "poll");
        attributes.put(CibaConfig.OIDC_CIBA_GRANT_ENABLED, Boolean.TRUE.toString());
        clientRep.setAttributes(attributes);
    });
    oauth.clientId(clientConfidentialId);
    oauth.scope("microprofile-jwt");
    // register profiles
    String json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Het Eerste Profiel").addExecutor(TestRaiseExeptionExecutorFactory.PROVIDER_ID, null).toRepresentation()).toString();
    updateProfiles(json);
    // register policies
    json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Het Eerste Beleid", Boolean.TRUE).addCondition(ClientScopesConditionFactory.PROVIDER_ID, createClientScopesConditionConfig(ClientScopesConditionFactory.OPTIONAL, Arrays.asList("microprofile-jwt"))).addProfile(PROFILE_NAME).toRepresentation()).toString();
    updatePolicies(json);
    // user Backchannel Authentication Request
    AuthenticationRequestAcknowledgement response = oauth.doBackchannelAuthenticationRequest(clientConfidentialId, clientConfidentialSecret, username, bindingMessage, null, null, additionalParameters);
    assertThat(response.getStatusCode(), is(equalTo(400)));
    assertThat(response.getError(), is(ClientPolicyEvent.BACKCHANNEL_AUTHENTICATION_REQUEST.name()));
    assertThat(response.getErrorDescription(), is("Exception thrown intentionally"));
    updatePolicies("{}");
    response = oauth.doBackchannelAuthenticationRequest(clientConfidentialId, clientConfidentialSecret, username, bindingMessage, null, null, additionalParameters);
    assertThat(response.getStatusCode(), is(equalTo(200)));
    Assert.assertNotNull(response.getAuthReqId());
    json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Het Eerste Beleid", Boolean.TRUE).addCondition(ClientScopesConditionFactory.PROVIDER_ID, createClientScopesConditionConfig(ClientScopesConditionFactory.OPTIONAL, Arrays.asList("microprofile-jwt"))).addProfile(PROFILE_NAME).toRepresentation()).toString();
    updatePolicies(json);
    OAuthClient.AccessTokenResponse tokenRes = oauth.doBackchannelAuthenticationTokenRequest(clientConfidentialId, clientConfidentialSecret, response.getAuthReqId());
    assertThat(tokenRes.getStatusCode(), is(equalTo(400)));
    assertThat(tokenRes.getError(), is(OAuthErrorException.INVALID_GRANT));
    assertThat(tokenRes.getErrorDescription(), is("Exception thrown intentionally"));
    updatePolicies("{}");
    // user Authentication Channel Request
    TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
    AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
    assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
    assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
    assertThat(authenticationChannelReq.getAdditionalParameters().get("user_device"), is(equalTo("mobile")));
    // user Authentication Channel completed
    doAuthenticationChannelCallback(testRequest);
    tokenRes = oauth.doBackchannelAuthenticationTokenRequest(clientConfidentialId, clientConfidentialSecret, response.getAuthReqId());
    assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
    AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
    assertThat(accessToken.getIssuedFor(), is(equalTo(clientConfidentialId)));
    RefreshToken refreshToken = oauth.parseRefreshToken(tokenRes.getRefreshToken());
    assertThat(refreshToken.getIssuedFor(), is(equalTo(clientConfidentialId)));
    assertThat(refreshToken.getAudience()[0], is(equalTo(refreshToken.getIssuer())));
    IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
    assertThat(idToken.getPreferredUsername(), is(equalTo(username)));
    assertThat(idToken.getIssuedFor(), is(equalTo(clientConfidentialId)));
    assertThat(idToken.getAudience()[0], is(equalTo(idToken.getIssuedFor())));
}
Also used : HashMap(java.util.HashMap) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ClientProfilesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder) ClientPoliciesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder) ClientPolicyBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientProfileBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder) RefreshToken(org.keycloak.representations.RefreshToken) AccessToken(org.keycloak.representations.AccessToken) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) IDToken(org.keycloak.representations.IDToken) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) Test(org.junit.Test)

Example 17 with AccessToken

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

the class CIBATest method doRefreshTokenRequest.

private OAuthClient.AccessTokenResponse doRefreshTokenRequest(String oldRefreshToken, String username, String sessionId, boolean isOfflineAccess) {
    OAuthClient.AccessTokenResponse tokenRes = oauth.doRefreshTokenRequest(oldRefreshToken, TEST_CLIENT_PASSWORD);
    assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
    AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
    assertThat(accessToken.getIssuedFor(), is(equalTo(TEST_CLIENT_NAME)));
    checkTokenExpiration(accessToken, tokenRes.getExpiresIn());
    RefreshToken refreshToken = oauth.parseRefreshToken(tokenRes.getRefreshToken());
    assertThat(refreshToken.getIssuedFor(), is(equalTo(TEST_CLIENT_NAME)));
    assertThat(refreshToken.getAudience()[0], is(equalTo(refreshToken.getIssuer())));
    if (!isOfflineAccess)
        checkTokenExpiration(refreshToken, tokenRes.getRefreshExpiresIn());
    IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
    assertThat(idToken.getPreferredUsername(), is(equalTo(username)));
    assertThat(idToken.getIssuedFor(), is(equalTo(TEST_CLIENT_NAME)));
    assertThat(idToken.getAudience()[0], is(equalTo(idToken.getIssuedFor())));
    checkTokenExpiration(idToken, tokenRes.getExpiresIn());
    events.expectRefresh(tokenRes.getRefreshToken(), sessionId).session(CoreMatchers.notNullValue(String.class)).user(AssertEvents.isUUID()).clearDetails().assertEvent();
    return tokenRes;
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) IDToken(org.keycloak.representations.IDToken)

Example 18 with AccessToken

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

the class CIBATest method testRequestTokenBeforeAuthenticationNotCompleted.

@Test
public void testRequestTokenBeforeAuthenticationNotCompleted() throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        final String username = "nutzername-rot";
        // prepare CIBA settings
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), TEST_CLIENT_NAME);
        assertThat(clientResource, notNullValue());
        clientRep = clientResource.toRepresentation();
        prepareCIBASettings(clientResource, clientRep);
        // user Backchannel Authentication Request
        AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, "kvoDKw98");
        // user Token Request before Authentication Channel completion
        OAuthClient.AccessTokenResponse tokenRes = oauth.doBackchannelAuthenticationTokenRequest(TEST_CLIENT_PASSWORD, response.getAuthReqId());
        assertThat(tokenRes.getStatusCode(), is(equalTo(400)));
        assertThat(tokenRes.getError(), is(OAuthErrorException.AUTHORIZATION_PENDING));
        // user Authentication Channel Request
        TestAuthenticationChannelRequest authenticationChannelReq = doAuthenticationChannelRequest("kvoDKw98");
        // user Authentication Channel completed
        doAuthenticationChannelCallback(authenticationChannelReq);
        setTimeOffset(6);
        // user Token Request after Authentication Channel completion
        tokenRes = oauth.doBackchannelAuthenticationTokenRequest(TEST_CLIENT_PASSWORD, response.getAuthReqId());
        assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
        IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
        assertThat(idToken.getPreferredUsername(), is(equalTo(username)));
        AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
        assertThat(accessToken, notNullValue());
    } finally {
        revertCIBASettings(clientResource, clientRep);
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) ClientResource(org.keycloak.admin.client.resource.ClientResource) IDToken(org.keycloak.representations.IDToken) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 19 with AccessToken

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

the class CIBATest method verifyBackchannelAuthenticationTokenRequest.

private void verifyBackchannelAuthenticationTokenRequest(OAuthClient.AccessTokenResponse tokenRes, String clientId, String username) {
    assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
    EventRepresentation event = events.expectAuthReqIdToToken(null, null).clearDetails().user(AssertEvents.isUUID()).client(clientId).assertEvent();
    AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
    assertThat(accessToken.getIssuedFor(), is(equalTo(clientId)));
    RefreshToken refreshToken = oauth.parseRefreshToken(tokenRes.getRefreshToken());
    assertThat(refreshToken.getIssuedFor(), is(equalTo(clientId)));
    assertThat(refreshToken.getAudience()[0], is(equalTo(refreshToken.getIssuer())));
    IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
    assertThat(idToken.getPreferredUsername(), is(equalTo(username)));
    assertThat(idToken.getIssuedFor(), is(equalTo(clientId)));
    assertThat(idToken.getAudience()[0], is(equalTo(idToken.getIssuedFor())));
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) AccessToken(org.keycloak.representations.AccessToken) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) IDToken(org.keycloak.representations.IDToken)

Example 20 with AccessToken

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

the class ClientPoliciesTest method successfulLoginAndLogoutWithPKCE.

private void successfulLoginAndLogoutWithPKCE(String clientId, String clientSecret, String userName, String userPassword) throws Exception {
    oauth.clientId(clientId);
    // 43
    String codeVerifier = "1a345A7890123456r8901c3456789012b45K7890l23";
    String codeChallenge = generateS256CodeChallenge(codeVerifier);
    oauth.codeChallenge(codeChallenge);
    oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_S256);
    oauth.nonce("bjapewiziIE083d");
    oauth.doLogin(userName, userPassword);
    EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    oauth.codeVerifier(codeVerifier);
    OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
    AccessToken token = oauth.verifyToken(res.getAccessToken());
    String userId = findUserByUsername(adminClient.realm(REALM_NAME), userName).getId();
    assertEquals(userId, token.getSubject());
    Assert.assertNotEquals(userName, token.getSubject());
    assertEquals(sessionId, token.getSessionState());
    assertEquals(clientId, token.getIssuedFor());
    String refreshTokenString = res.getRefreshToken();
    RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString);
    assertEquals(sessionId, refreshToken.getSessionState());
    assertEquals(clientId, refreshToken.getIssuedFor());
    OAuthClient.AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(refreshTokenString, clientSecret);
    assertEquals(200, refreshResponse.getStatusCode());
    events.expectRefresh(refreshToken.getId(), sessionId).client(clientId).assertEvent();
    AccessToken refreshedToken = oauth.verifyToken(refreshResponse.getAccessToken());
    RefreshToken refreshedRefreshToken = oauth.parseRefreshToken(refreshResponse.getRefreshToken());
    assertEquals(sessionId, refreshedToken.getSessionState());
    assertEquals(sessionId, refreshedRefreshToken.getSessionState());
    assertEquals(findUserByUsername(adminClient.realm(REALM_NAME), userName).getId(), refreshedToken.getSubject());
    doIntrospectAccessToken(refreshResponse, userName, clientId, clientSecret);
    doTokenRevoke(refreshResponse.getRefreshToken(), clientId, clientSecret, userId, false);
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) EventRepresentation(org.keycloak.representations.idm.EventRepresentation)

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