Search in sources :

Example 11 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class DockerAuthV2Protocol method authenticated.

@Override
public Response authenticated(final AuthenticationSessionModel authSession, final UserSessionModel userSession, final ClientSessionContext clientSessionCtx) {
    // First, create a base response token with realm + user values populated
    final AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
    final ClientModel client = clientSession.getClient();
    DockerResponseToken responseToken = new DockerResponseToken().id(KeycloakModelUtils.generateId()).type(TokenUtil.TOKEN_TYPE_BEARER).issuer(authSession.getClientNote(DockerAuthV2Protocol.ISSUER)).subject(userSession.getUser().getUsername()).issuedNow().audience(client.getClientId()).issuedFor(client.getClientId());
    // since realm access token is given in seconds
    final int accessTokenLifespan = realm.getAccessTokenLifespan();
    responseToken.notBefore(responseToken.getIssuedAt()).expiration(responseToken.getIssuedAt() + accessTokenLifespan);
    // Next, allow mappers to decorate the token to add/remove scopes as appropriate
    AtomicReference<DockerResponseToken> finalResponseToken = new AtomicReference<>(responseToken);
    ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx).filter(mapper -> mapper.getValue() instanceof DockerAuthV2AttributeMapper).filter(mapper -> ((DockerAuthV2AttributeMapper) mapper.getValue()).appliesTo(finalResponseToken.get())).forEach(mapper -> finalResponseToken.set(((DockerAuthV2AttributeMapper) mapper.getValue()).transformDockerResponseToken(finalResponseToken.get(), mapper.getKey(), session, userSession, clientSession)));
    responseToken = finalResponseToken.get();
    try {
        // Finally, construct the response to the docker client with the token + metadata
        if (event.getEvent() != null && EventType.LOGIN.equals(event.getEvent().getType())) {
            final KeyManager.ActiveRsaKey activeKey = session.keys().getActiveRsaKey(realm);
            final String encodedToken = new JWSBuilder().kid(new DockerKeyIdentifier(activeKey.getPublicKey()).toString()).type("JWT").jsonContent(responseToken).rsa256(activeKey.getPrivateKey());
            final String expiresInIso8601String = new SimpleDateFormat(ISO_8601_DATE_FORMAT).format(new Date(responseToken.getIssuedAt() * 1000L));
            final DockerResponse responseEntity = new DockerResponse().setToken(encodedToken).setExpires_in(accessTokenLifespan).setIssued_at(expiresInIso8601String);
            return new ResponseBuilderImpl().status(Response.Status.OK).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(responseEntity).build();
        } else {
            logger.errorv("Unable to handle request for event type {0}.  Currently only LOGIN event types are supported by docker protocol.", event.getEvent() == null ? "null" : event.getEvent().getType());
            throw new ErrorResponseException("invalid_request", "Event type not supported", Response.Status.BAD_REQUEST);
        }
    } catch (final InstantiationException e) {
        logger.errorv("Error attempting to create Key ID for Docker JOSE header: ", e.getMessage());
        throw new ErrorResponseException("token_error", "Unable to construct JOSE header for JWT", Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : DockerAuthV2AttributeMapper(org.keycloak.protocol.docker.mapper.DockerAuthV2AttributeMapper) ClientModel(org.keycloak.models.ClientModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Date(java.util.Date) Logger(org.jboss.logging.Logger) SimpleDateFormat(java.text.SimpleDateFormat) ResponseBuilderImpl(org.jboss.resteasy.specimpl.ResponseBuilderImpl) AtomicReference(java.util.concurrent.atomic.AtomicReference) KeyManager(org.keycloak.models.KeyManager) TokenUtil(org.keycloak.util.TokenUtil) MediaType(javax.ws.rs.core.MediaType) ClientSessionContext(org.keycloak.models.ClientSessionContext) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) EventBuilder(org.keycloak.events.EventBuilder) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) DockerResponseToken(org.keycloak.representations.docker.DockerResponseToken) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) EventType(org.keycloak.events.EventType) UserSessionModel(org.keycloak.models.UserSessionModel) DockerResponse(org.keycloak.representations.docker.DockerResponse) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) ProtocolMapperUtils(org.keycloak.protocol.ProtocolMapperUtils) UriInfo(javax.ws.rs.core.UriInfo) DockerAuthV2AttributeMapper(org.keycloak.protocol.docker.mapper.DockerAuthV2AttributeMapper) LoginProtocol(org.keycloak.protocol.LoginProtocol) DockerResponse(org.keycloak.representations.docker.DockerResponse) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) DockerResponseToken(org.keycloak.representations.docker.DockerResponseToken) Date(java.util.Date) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) ClientModel(org.keycloak.models.ClientModel) ResponseBuilderImpl(org.jboss.resteasy.specimpl.ResponseBuilderImpl) ErrorResponseException(org.keycloak.services.ErrorResponseException) KeyManager(org.keycloak.models.KeyManager) SimpleDateFormat(java.text.SimpleDateFormat)

Example 12 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionProviderOfflineTest method testOnRealmRemoved.

@Test
@ModelTest
public void testOnRealmRemoved(KeycloakSession session) {
    AtomicReference<String> userSessionID = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR1) -> {
        currentSession = sessionRR1;
        RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
        fooRealm.setSsoSessionIdleTimeout(1800);
        fooRealm.setSsoSessionMaxLifespan(36000);
        fooRealm.setOfflineSessionIdleTimeout(2592000);
        fooRealm.setOfflineSessionMaxLifespan(5184000);
        fooRealm.addClient("foo-app");
        currentSession.users().addUser(fooRealm, "user3");
        UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
        userSessionID.set(userSession.getId());
        createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR2) -> {
        currentSession = sessionRR2;
        sessionManager = new UserSessionManager(currentSession);
        // Persist offline session
        RealmModel fooRealm = currentSession.realms().getRealm("foo");
        UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
        createOfflineSessionIncludeClientSessions(currentSession, userSession);
        UserSessionModel offlineUserSession = sessionManager.findOfflineUserSession(fooRealm, userSession.getId());
        Assert.assertEquals(offlineUserSession.getAuthenticatedClientSessions().size(), 1);
        AuthenticatedClientSessionModel offlineClientSession = offlineUserSession.getAuthenticatedClientSessions().values().iterator().next();
        Assert.assertEquals("foo-app", offlineClientSession.getClient().getClientId());
        Assert.assertEquals("user3", offlineClientSession.getUserSession().getUser().getUsername());
        // Remove realm
        RealmManager realmMgr = new RealmManager(currentSession);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR3) -> {
        currentSession = sessionRR3;
        RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
        fooRealm.addClient("foo-app");
        currentSession.users().addUser(fooRealm, "user3");
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR4) -> {
        currentSession = sessionRR4;
        RealmModel fooRealm = currentSession.realms().getRealm("foo");
        Assert.assertEquals(0, currentSession.sessions().getOfflineSessionsCount(fooRealm, fooRealm.getClientByClientId("foo-app")));
        // Cleanup
        RealmManager realmMgr = new RealmManager(currentSession);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserSessionModel(org.keycloak.models.UserSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 13 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method testUpdateClientSession.

@Test
@ModelTest
public void testUpdateClientSession(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);
    String userSessionId = sessions[0].getId();
    String clientUUID = realm.getClientByClientId("test-app").getId();
    UserSessionModel userSession = session.sessions().getUserSession(realm, userSessionId);
    AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().get(clientUUID);
    int time = clientSession.getTimestamp();
    assertNull(clientSession.getAction());
    clientSession.setAction(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name());
    clientSession.setTimestamp(time + 10);
    AuthenticatedClientSessionModel updated = session.sessions().getUserSession(realm, userSessionId).getAuthenticatedClientSessions().get(clientUUID);
    assertEquals(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name(), updated.getAction());
    assertEquals(time + 10, updated.getTimestamp());
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 14 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method testTransientUserSession.

@Test
@ModelTest
public void testTransientUserSession(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    ClientModel client = realm.getClientByClientId("test-app");
    String userSessionId = UUID.randomUUID().toString();
    // create an user session, but don't persist it to infinispan
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> {
        long sessionsBefore = session1.sessions().getActiveUserSessions(realm, client);
        UserSessionModel userSession = session1.sessions().createUserSession(userSessionId, realm, session1.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.1", "form", true, null, null, UserSessionModel.SessionPersistenceState.TRANSIENT);
        AuthenticatedClientSessionModel clientSession = session1.sessions().createClientSession(realm, client, userSession);
        assertEquals(userSession, clientSession.getUserSession());
        assertSession(userSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.1", userSession.getStarted(), userSession.getStarted(), "test-app");
        // Can find session by ID in current transaction
        UserSessionModel foundSession = session1.sessions().getUserSession(realm, userSessionId);
        Assert.assertEquals(userSession, foundSession);
        // Count of sessions should be still the same
        Assert.assertEquals(sessionsBefore, session1.sessions().getActiveUserSessions(realm, client));
    });
    // create an user session whose last refresh exceeds the max session idle timeout.
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession session1) -> {
        UserSessionModel userSession = session1.sessions().getUserSession(realm, userSessionId);
        Assert.assertNull(userSession);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 15 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionProviderTest method testAuthenticatedClientSessions.

@Test
@ModelTest
public void testAuthenticatedClientSessions(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    realm.setSsoSessionIdleTimeout(1800);
    realm.setSsoSessionMaxLifespan(36000);
    UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "127.0.0.2", "form", true, null, null);
    ClientModel client1 = realm.getClientByClientId("test-app");
    ClientModel client2 = realm.getClientByClientId("third-party");
    // Create client1 session
    AuthenticatedClientSessionModel clientSession1 = session.sessions().createClientSession(realm, client1, userSession);
    clientSession1.setAction("foo1");
    int currentTime1 = Time.currentTime();
    clientSession1.setTimestamp(currentTime1);
    // Create client2 session
    AuthenticatedClientSessionModel clientSession2 = session.sessions().createClientSession(realm, client2, userSession);
    clientSession2.setAction("foo2");
    int currentTime2 = Time.currentTime();
    clientSession2.setTimestamp(currentTime2);
    // Ensure sessions are here
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    Map<String, AuthenticatedClientSessionModel> clientSessions = userSession.getAuthenticatedClientSessions();
    Assert.assertEquals(2, clientSessions.size());
    testAuthenticatedClientSession(clientSessions.get(client1.getId()), "test-app", userSession.getId(), "foo1", currentTime1);
    testAuthenticatedClientSession(clientSessions.get(client2.getId()), "third-party", userSession.getId(), "foo2", currentTime2);
    // Update session1
    clientSessions.get(client1.getId()).setAction("foo1-updated");
    // Ensure updated
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    clientSessions = userSession.getAuthenticatedClientSessions();
    testAuthenticatedClientSession(clientSessions.get(client1.getId()), "test-app", userSession.getId(), "foo1-updated", currentTime1);
    // Rewrite session2
    clientSession2 = session.sessions().createClientSession(realm, client2, userSession);
    clientSession2.setAction("foo2-rewrited");
    int currentTime3 = Time.currentTime();
    clientSession2.setTimestamp(currentTime3);
    // Ensure updated
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    clientSessions = userSession.getAuthenticatedClientSessions();
    Assert.assertEquals(2, clientSessions.size());
    testAuthenticatedClientSession(clientSessions.get(client1.getId()), "test-app", userSession.getId(), "foo1-updated", currentTime1);
    testAuthenticatedClientSession(clientSessions.get(client2.getId()), "third-party", userSession.getId(), "foo2-rewrited", currentTime3);
    // remove session
    clientSession1 = userSession.getAuthenticatedClientSessions().get(client1.getId());
    clientSession1.detachFromUserSession();
    userSession = session.sessions().getUserSession(realm, userSession.getId());
    clientSessions = userSession.getAuthenticatedClientSessions();
    Assert.assertEquals(1, clientSessions.size());
    Assert.assertNull(clientSessions.get(client1.getId()));
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)59 UserSessionModel (org.keycloak.models.UserSessionModel)35 RealmModel (org.keycloak.models.RealmModel)25 ClientModel (org.keycloak.models.ClientModel)23 Test (org.junit.Test)16 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)13 UserModel (org.keycloak.models.UserModel)12 KeycloakSession (org.keycloak.models.KeycloakSession)11 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)11 HashMap (java.util.HashMap)10 Map (java.util.Map)9 ClientSessionContext (org.keycloak.models.ClientSessionContext)9 LinkedList (java.util.LinkedList)8 DefaultClientSessionContext (org.keycloak.services.util.DefaultClientSessionContext)8 OAuthErrorException (org.keycloak.OAuthErrorException)6 VerificationException (org.keycloak.common.VerificationException)6 AccessToken (org.keycloak.representations.AccessToken)6 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)6 HashSet (java.util.HashSet)5 List (java.util.List)5