Search in sources :

Example 1 with RefreshToken

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

the class AbstractShowTokensServlet method renderTokens.

protected String renderTokens(HttpServletRequest req) throws ServletException, IOException {
    RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
    String accessTokenPretty = JsonSerialization.writeValueAsPrettyString(ctx.getToken());
    RefreshToken refreshToken;
    try {
        refreshToken = new JWSInput(ctx.getRefreshToken()).readJsonContent(RefreshToken.class);
    } catch (JWSInputException e) {
        throw new IOException(e);
    }
    String refreshTokenPretty = JsonSerialization.writeValueAsPrettyString(refreshToken);
    return new StringBuilder("<span id=\"accessToken\">" + accessTokenPretty + "</span>").append("<span id=\"refreshToken\">" + refreshTokenPretty + "</span>").append("<span id=\"accessTokenString\">" + ctx.getTokenString() + "</span>").append("<span id=\"refreshTokenString\">" + ctx.getRefreshToken() + "</span>").toString();
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) IOException(java.io.IOException)

Example 2 with RefreshToken

use of org.keycloak.representations.RefreshToken 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 3 with RefreshToken

use of org.keycloak.representations.RefreshToken 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 4 with RefreshToken

use of org.keycloak.representations.RefreshToken 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 5 with RefreshToken

use of org.keycloak.representations.RefreshToken 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

RefreshToken (org.keycloak.representations.RefreshToken)68 OAuthClient (org.keycloak.testsuite.util.OAuthClient)50 AccessToken (org.keycloak.representations.AccessToken)45 Test (org.junit.Test)34 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)29 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)27 JWSInput (org.keycloak.jose.jws.JWSInput)10 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)6 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)6 IOException (java.io.IOException)5 HttpResponse (org.apache.http.HttpResponse)5 JWSHeader (org.keycloak.jose.jws.JWSHeader)5 IDToken (org.keycloak.representations.IDToken)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)4 ClientResource (org.keycloak.admin.client.resource.ClientResource)4 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)4 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)4 AccessTokenResponse (org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse)4 KeyPair (java.security.KeyPair)3 PrivateKey (java.security.PrivateKey)3