Search in sources :

Example 11 with RefreshToken

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

the class RefreshTokenTest method refreshTokenAfterUserAdminLogoutEndpointAndLoginAgain.

@Test
@AuthServerContainerExclude(AuthServerContainerExclude.AuthServer.REMOTE)
public void refreshTokenAfterUserAdminLogoutEndpointAndLoginAgain() {
    try {
        String refreshToken1 = loginAndForceNewLoginPage();
        RefreshToken refreshTokenParsed1 = oauth.parseRefreshToken(refreshToken1);
        String userId = refreshTokenParsed1.getSubject();
        UserResource user = adminClient.realm("test").users().get(userId);
        user.logout();
        // Set time offset to 2 (Just to simulate to be more close to real situation)
        setTimeOffset(2);
        // Continue with login
        WaitUtils.waitForPageToLoad();
        loginPage.login("password");
        assertFalse(loginPage.isCurrent());
        OAuthClient.AccessTokenResponse tokenResponse2 = null;
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        tokenResponse2 = oauth.doAccessTokenRequest(code, "password");
        setTimeOffset(4);
        // Now try refresh with the original refreshToken1 created in logged-out userSession. It should fail
        OAuthClient.AccessTokenResponse responseReuseExceeded = oauth.doRefreshTokenRequest(refreshToken1, "password");
        assertEquals(400, responseReuseExceeded.getStatusCode());
        setTimeOffset(6);
        // Finally try with valid refresh token
        responseReuseExceeded = oauth.doRefreshTokenRequest(tokenResponse2.getRefreshToken(), "password");
        assertEquals(200, responseReuseExceeded.getStatusCode());
    } finally {
        // Need to reset not-before of user, which was updated during user.logout()
        testingClient.server().run(session -> {
            RealmModel realm = session.realms().getRealmByName("test");
            UserModel user = session.users().getUserByUsername(realm, "test-user@localhost");
            session.users().setNotBeforeForUser(realm, user, 0);
        });
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) UserResource(org.keycloak.admin.client.resource.UserResource) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 12 with RefreshToken

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

the class RefreshTokenTest method refreshTokenReuseTokenWithRefreshTokensRevokedAfterSingleReuse.

@Test
public void refreshTokenReuseTokenWithRefreshTokensRevokedAfterSingleReuse() throws Exception {
    try {
        RealmManager.realm(adminClient.realm("test")).revokeRefreshToken(true).refreshTokenMaxReuse(1);
        oauth.doLogin("test-user@localhost", "password");
        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse initialResponse = oauth.doAccessTokenRequest(code, "password");
        RefreshToken initialRefreshToken = oauth.parseRefreshToken(initialResponse.getRefreshToken());
        events.expectCodeToToken(codeId, sessionId).assertEvent();
        setTimeOffset(2);
        // Initial refresh.
        OAuthClient.AccessTokenResponse responseFirstUse = oauth.doRefreshTokenRequest(initialResponse.getRefreshToken(), "password");
        RefreshToken newTokenFirstUse = oauth.parseRefreshToken(responseFirstUse.getRefreshToken());
        assertEquals(200, responseFirstUse.getStatusCode());
        events.expectRefresh(initialRefreshToken.getId(), sessionId).assertEvent();
        setTimeOffset(4);
        // Second refresh (allowed).
        OAuthClient.AccessTokenResponse responseFirstReuse = oauth.doRefreshTokenRequest(initialResponse.getRefreshToken(), "password");
        RefreshToken newTokenFirstReuse = oauth.parseRefreshToken(responseFirstReuse.getRefreshToken());
        assertEquals(200, responseFirstReuse.getStatusCode());
        events.expectRefresh(initialRefreshToken.getId(), sessionId).assertEvent();
        setTimeOffset(6);
        // Token reused twice, became invalid.
        OAuthClient.AccessTokenResponse responseSecondReuse = oauth.doRefreshTokenRequest(initialResponse.getRefreshToken(), "password");
        assertEquals(400, responseSecondReuse.getStatusCode());
        events.expectRefresh(initialRefreshToken.getId(), sessionId).removeDetail(Details.TOKEN_ID).removeDetail(Details.UPDATED_REFRESH_TOKEN_ID).error("invalid_token").assertEvent();
        setTimeOffset(8);
        // Refresh token from first use became invalid.
        OAuthClient.AccessTokenResponse responseUseOfInvalidatedRefreshToken = oauth.doRefreshTokenRequest(responseFirstUse.getRefreshToken(), "password");
        assertEquals(400, responseUseOfInvalidatedRefreshToken.getStatusCode());
        events.expectRefresh(newTokenFirstUse.getId(), sessionId).removeDetail(Details.TOKEN_ID).removeDetail(Details.UPDATED_REFRESH_TOKEN_ID).error("invalid_token").assertEvent();
        setTimeOffset(10);
        // Refresh token from reuse is not valid. Client session was invalidated
        OAuthClient.AccessTokenResponse responseUseOfValidRefreshToken = oauth.doRefreshTokenRequest(responseFirstReuse.getRefreshToken(), "password");
        assertEquals(400, responseUseOfValidRefreshToken.getStatusCode());
        events.expectRefresh(newTokenFirstReuse.getId(), sessionId).removeDetail(Details.TOKEN_ID).removeDetail(Details.UPDATED_REFRESH_TOKEN_ID).error("invalid_token").assertEvent();
    } finally {
        setTimeOffset(0);
        RealmManager.realm(adminClient.realm("test")).refreshTokenMaxReuse(0).revokeRefreshToken(false);
    }
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 13 with RefreshToken

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

the class RefreshTokenTest method refreshTokenClientDisabled.

@Test
public void refreshTokenClientDisabled() throws Exception {
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    String refreshTokenString = response.getRefreshToken();
    RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString);
    events.expectCodeToToken(codeId, sessionId).assertEvent();
    try {
        ClientManager.realm(adminClient.realm("test")).clientId(oauth.getClientId()).enabled(false);
        setTimeOffset(2);
        response = oauth.doRefreshTokenRequest(refreshTokenString, "password");
        assertEquals(400, response.getStatusCode());
        assertEquals("unauthorized_client", response.getError());
        events.expectRefresh(refreshToken.getId(), sessionId).user((String) null).session((String) null).clearDetails().error(Errors.CLIENT_DISABLED).assertEvent();
    } finally {
        ClientManager.realm(adminClient.realm("test")).clientId(oauth.getClientId()).enabled(true);
    }
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 14 with RefreshToken

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

the class ResourceOwnerPasswordCredentialsGrantTest method grantAccessTokenLogout.

@Test
public void grantAccessTokenLogout() throws Exception {
    oauth.clientId("resource-owner");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "test-user@localhost", "password");
    assertEquals(200, response.getStatusCode());
    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
    events.expectLogin().client("resource-owner").session(accessToken.getSessionState()).detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT).detail(Details.CLIENT_AUTH_METHOD, ClientIdAndSecretAuthenticator.PROVIDER_ID).assertEvent();
    HttpResponse logoutResponse = oauth.doLogout(response.getRefreshToken(), "secret");
    assertEquals(204, logoutResponse.getStatusLine().getStatusCode());
    events.expectLogout(accessToken.getSessionState()).client("resource-owner").removeDetail(Details.REDIRECT_URI).assertEvent();
    response = oauth.doRefreshTokenRequest(response.getRefreshToken(), "secret");
    assertEquals(400, response.getStatusCode());
    assertEquals("invalid_grant", response.getError());
    events.expectRefresh(refreshToken.getId(), refreshToken.getSessionState()).client("resource-owner").removeDetail(Details.TOKEN_ID).removeDetail(Details.UPDATED_REFRESH_TOKEN_ID).error(Errors.INVALID_TOKEN).assertEvent();
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) HttpResponse(org.apache.http.HttpResponse) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 15 with RefreshToken

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

the class ResourceOwnerPasswordCredentialsGrantTest method grantAccessTokenWithDynamicScope.

@Test
@EnableFeature(value = Profile.Feature.DYNAMIC_SCOPES, skipRestart = true)
public void grantAccessTokenWithDynamicScope() throws Exception {
    ClientScopeRepresentation clientScope = new ClientScopeRepresentation();
    clientScope.setName("dynamic-scope");
    clientScope.setAttributes(new HashMap<String, String>() {

        {
            put(ClientScopeModel.IS_DYNAMIC_SCOPE, "true");
            put(ClientScopeModel.DYNAMIC_SCOPE_REGEXP, "dynamic-scope:*");
        }
    });
    clientScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    RealmResource realmResource = adminClient.realm("test");
    try (Response response = realmResource.clientScopes().create(clientScope)) {
        String scopeId = ApiUtil.getCreatedId(response);
        getCleanup().addClientScopeId(scopeId);
        ClientResource resourceOwnerPublicClient = ApiUtil.findClientByClientId(realmResource, "resource-owner-public");
        ClientRepresentation testAppRep = resourceOwnerPublicClient.toRepresentation();
        resourceOwnerPublicClient.update(testAppRep);
        resourceOwnerPublicClient.addOptionalClientScope(scopeId);
    }
    oauth.scope("dynamic-scope:123");
    oauth.clientId("resource-owner-public");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "direct-login", "password");
    assertTrue(response.getScope().contains("dynamic-scope:123"));
    assertEquals(200, response.getStatusCode());
    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
    events.expectLogin().client("resource-owner-public").user(userId).session(accessToken.getSessionState()).detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).detail(Details.USERNAME, "direct-login").removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT).assertEvent();
    assertTrue(accessToken.getScope().contains("dynamic-scope:123"));
}
Also used : Response(javax.ws.rs.core.Response) HttpResponse(org.apache.http.HttpResponse) RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) AccessToken(org.keycloak.representations.AccessToken) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test) EnableFeature(org.keycloak.testsuite.arquillian.annotation.EnableFeature)

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