private UserSessionModel findValidSession(AccessToken token, ClientModel client, RealmModel realm, KeycloakSession session) { UserSessionModel userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), false, client.getId()); UserSessionModel offlineUserSession = null; if (AuthenticationManager.isSessionValid(realm, userSession)) { return userSession; } else { offlineUserSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), true, client.getId()); if (AuthenticationManager.isOfflineSessionValid(realm, offlineUserSession)) { return offlineUserSession; } } if (userSession == null && offlineUserSession == null) { LOG.debug("User session not found or doesn't have client attached on it"); } else { LOG.debug("Session expired"); } return null; }
public ExampleRestResource(KeycloakSession session) { this.session = session; this.auth = new AppAuthManager().authenticateBearerToken(session, session.getContext().getRealm()); }
@Override public void backchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) { String logoutUrl = clientSession.getRedirectUri(); String serviceTicket = clientSession.getNote(CASLoginProtocol.SESSION_SERVICE_TICKET); //check if session is fully authenticated (i.e. serviceValidate has been called) if (serviceTicket != null && !serviceTicket.isEmpty()) { sendSingleLogoutRequest(logoutUrl, serviceTicket); } ClientModel client = clientSession.getClient(); new ResourceAdminManager(session).logoutClientSession(uriInfo.getRequestUri(), realm, client, clientSession); }
private void setupAuth() { AppAuthManager authManager = new AppAuthManager(); String tokenString = authManager.extractAuthorizationHeaderToken(headers); RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(realmName); AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers); if (authResult == null) { throw new NotAuthorizedException("Bearer"); = realm.getName().equals(Config.getAdminRealm()) ? this.realm.getMasterAdminClient() : this.realm.getClientByClientId(realmManager.getRealmAdminClientId(this.realm)); UserModel user = authResult.getUser();
@POST @Path("/remove-expired") @Produces(MediaType.APPLICATION_JSON) public Response removeExpired(@QueryParam("realm") final String name) { RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(name); if (realm == null) { throw new NotFoundException("Realm not found"); } session.sessions().removeExpired(realm); return Response.ok().build(); }
@GET @NoCache public Response logout(@QueryParam(CASLoginProtocol.SERVICE_PARAM) String service) { checkClient(service); AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(session, realm, false); if (authResult != null) { UserSessionModel userSession = authResult.getSession(); userSession.setNote(AuthenticationManager.KEYCLOAK_LOGOUT_PROTOCOL, CASLoginProtocol.LOGIN_PROTOCOL); if (redirectUri != null) userSession.setNote(CASLoginProtocol.LOGOUT_REDIRECT_URI, redirectUri); logger.debug("Initiating CAS browser logout"); Response response = AuthenticationManager.browserLogout(session, realm, authResult.getSession(), session.getContext().getUri(), clientConnection, headers, null); logger.debug("finishing CAS browser logout"); return response; } return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.FAILED_LOGOUT); }
private void initRoles(KeycloakSession session) { LOG.debug("BeerResourceProviderFactory::initRoles"); ClientModel client; List<RealmModel> realms = session.realms().getRealms(); RealmManager manager = new RealmManager(session); for (RealmModel realm : realms) { client = realm.getMasterAdminClient(); if (client.getRole(ROLE_VIEW_BEER) == null && client.getRole(ROLE_MANAGE_BEER) == null) { addMasterAdminRoles(manager, realm); } if (!realm.getName().equals(Config.getAdminRealm())) { client = realm.getClientByClientId(manager.getRealmAdminClientId(realm)); if (client.getRole(ROLE_VIEW_BEER) == null && client.getRole(ROLE_MANAGE_BEER) == null) { addRealmAdminRoles(manager, realm); } } } }
if (requireReauth && AuthenticationManager.isSSOAuthentication(clientSession)) { event.error(Errors.SESSION_EXPIRED); throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Interactive authentication was requested but not performed", Response.Status.BAD_REQUEST); if (!AuthenticationManager.isSessionValid(realm, userSession)) { event.error(Errors.USER_SESSION_NOT_FOUND); throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Session not active", Response.Status.BAD_REQUEST);
@GET @Path("/verify-code") @Produces(MediaType.APPLICATION_JSON) public String verifyCode(@QueryParam("realm") String realmName, @QueryParam("code") String code) { RealmModel realm = session.realms().getRealm(realmName); try { ClientSessionCode accessCode = ClientSessionCode.parse(code, session, realm); if (accessCode == null) { throw new AssertionError("Invalid code"); } return accessCode.getClientSession().getId(); } catch (Throwable t) { throw new AssertionError("Failed to parse code", t); } }
private void addMasterAdminRoles(RealmManager manager, RealmModel realm) { RealmModel master = manager.getRealmByName(Config.getAdminRealm()); RoleModel admin = master.getRole(AdminRoles.ADMIN); ClientModel client = realm.getMasterAdminClient(); addRoles(client, admin); }
private void realmPostCreate(RealmModel.RealmPostCreateEvent event) { RealmModel realm = event.getCreatedRealm(); RealmManager manager = new RealmManager(event.getKeycloakSession()); addMasterAdminRoles(manager, realm); if (!realm.getName().equals(Config.getAdminRealm())) addRealmAdminRoles(manager, realm); }
private void tryCreateMasterRealmAdminUser() { KeycloakSession session = getSessionFactory().create(); ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session); AdminUser admin = keycloakServerProperties.getAdminUser(); try { session.getTransactionManager().begin(); applianceBootstrap.createMasterRealmUser(admin.getUsername(), admin.getPassword()); session.getTransactionManager().commit(); } catch (Exception ex) { LOG.warn("Couldn't create keycloak master admin user: {}", ex.getMessage()); session.getTransactionManager().rollback(); } session.close(); }
public ApplicationsBean(KeycloakSession session, RealmModel realm, UserModel user) { Set<ClientModel> offlineClients = new UserSessionManager(session).findClientsWithOfflineToken(realm, user);
private void addRealmAdminRoles(RealmManager manager, RealmModel realm) { ClientModel client = realm.getClientByClientId(manager.getRealmAdminClientId(realm)); RoleModel admin = client.getRole(AdminRoles.REALM_ADMIN); addRoles(client, admin); }
am = new ApplicationManager(this); am.setOnInstalledPackage(new OnInstalledPackage() {
@GET @Path("logout_response") public Response logoutResponse(@Context UriInfo uriInfo, @QueryParam("state") String state) { UserSessionModel userSession = session.sessions().getUserSession(realm, state); if (userSession == null) { logger.error("no valid user session"); EventBuilder event = new EventBuilder(realm, session, clientConnection); event.event(EventType.LOGOUT); event.error(Errors.USER_SESSION_NOT_FOUND); return ErrorPage.error(session, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR); } if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) { logger.error("usersession in different state"); EventBuilder event = new EventBuilder(realm, session, clientConnection); event.event(EventType.LOGOUT); event.error(Errors.USER_SESSION_NOT_FOUND); return ErrorPage.error(session, Messages.SESSION_NOT_ACTIVE); } return AuthenticationManager.finishBrowserLogout(session, realm, userSession, uriInfo, clientConnection, headers); }
@POST @Path("/remove-user-sessions") @Produces(MediaType.APPLICATION_JSON) public Response removeUserSessions(@QueryParam("realm") final String realmName) { RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(realmName); if (realm == null) { throw new NotFoundException("Realm not found"); } session.sessions().removeUserSessions(realm); return Response.ok().build(); }
@GET @Path("/get-user-session") @Produces(MediaType.APPLICATION_JSON) public Integer getLastSessionRefresh(@QueryParam("realm") final String name, @QueryParam("session") final String sessionId) { RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(name); if (realm == null) { throw new NotFoundException("Realm not found"); } UserSessionModel sessionModel = session.sessions().getUserSession(realm, sessionId); if (sessionModel == null) { throw new NotFoundException("Session not found"); } return sessionModel.getLastSessionRefresh(); }
@POST @Path("/remove-user-session") @Produces(MediaType.APPLICATION_JSON) public Response removeUserSession(@QueryParam("realm") final String name, @QueryParam("session") final String sessionId) { RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(name); if (realm == null) { throw new NotFoundException("Realm not found"); } UserSessionModel sessionModel = session.sessions().getUserSession(realm, sessionId); if (sessionModel == null) { throw new NotFoundException("Session not found"); } session.sessions().removeUserSession(realm, sessionModel); return Response.ok().build(); }