org.keycloak.services.managers.AuthenticationManager Java Examples

The following examples show how to use org.keycloak.services.managers.AuthenticationManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SAMLEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response handleLogoutResponse(SAMLDocumentHolder holder, StatusResponseType responseType, String relayState) {
    if (relayState == null) {
        logger.error("no valid user session");
        event.event(EventType.LOGOUT);
        event.error(Errors.USER_SESSION_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
    }
    UserSessionModel userSession = session.sessions().getUserSession(realm, relayState);
    if (userSession == null) {
        logger.error("no valid user session");
        event.event(EventType.LOGOUT);
        event.error(Errors.USER_SESSION_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
    }
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        logger.error("usersession in different state");
        event.event(EventType.LOGOUT);
        event.error(Errors.USER_SESSION_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
    }
    return AuthenticationManager.finishBrowserLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers);
}
 
Example #2
Source File: SessionTimeoutValidationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@ModelTest
public  void testIsSessionValid(KeycloakSession session) {
    
    // KEYCLOAK-9833 Large SSO Session Idle/SSO Session Max causes login failure
    RealmModel realm = session.realms().getRealmByName("test");
    int ssoSessionIdleTimeoutOrig = realm.getSsoSessionIdleTimeout();
    int ssoSessionMaxLifespanOrig = realm.getSsoSessionMaxLifespan();
    UserSessionModel userSessionModel =
        session.sessions().createUserSession(
                                             realm,
                                             session.users().getUserByUsername("user1", realm),
                                             "user1", "127.0.0.1", "form", true, null, null
                                             );

    realm.setSsoSessionIdleTimeout(Integer.MAX_VALUE);
    Assert.assertTrue("Session validataion with large SsoSessionIdleTimeout failed",
                      AuthenticationManager.isSessionValid(realm, userSessionModel));
    
    realm.setSsoSessionMaxLifespan(Integer.MAX_VALUE);
    Assert.assertTrue("Session validataion with large SsoSessionMaxLifespan failed",
                      AuthenticationManager.isSessionValid(realm, userSessionModel));
    
    realm.setSsoSessionIdleTimeout(ssoSessionIdleTimeoutOrig);
    realm.setSsoSessionMaxLifespan(ssoSessionMaxLifespanOrig);
}
 
Example #3
Source File: LogoutEndpoint.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
private MultivaluedMap<String, String> createLoginFormData(AuthenticationFlowContext context) {

        MultivaluedMap<String, String> formData = new MultivaluedMapImpl<>();
        String loginHint = context.getAuthenticationSession().getClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM);
        String rememberMeUsername = AuthenticationManager.getRememberMeUsername(context.getRealm(), context.getHttpRequest().getHttpHeaders());

        if (loginHint != null || rememberMeUsername != null) {
            if (loginHint != null) {
                formData.add(AuthenticationManager.FORM_USERNAME, loginHint);
            } else {
                formData.add(AuthenticationManager.FORM_USERNAME, rememberMeUsername);
                formData.add("rememberMe", "on");
            }
        }
        return formData;
    }
 
Example #5
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
protected Response challenge(AuthenticationFlowContext context, String error) {

    String useAjax = getConfigProperty(context, USE_AXJAX_CONFIG_PROPERTY, "true");
    String loginHint = context.getHttpRequest().getUri().getQueryParameters().getFirst(OIDCLoginProtocol.LOGIN_HINT_PARAM);

    LoginFormsProvider usernameLoginForm = createSelectUserForm(context, error)
            .setAttribute("useAjax", "true".equals(useAjax));

    if (loginHint != null) {
        MultivaluedHashMap<String, String> formData = new MultivaluedHashMap<>();
        formData.add(AuthenticationManager.FORM_USERNAME, loginHint);
        usernameLoginForm.setAttribute("login", new LoginBean(formData));
    }

    return usernameLoginForm
            .createForm("select-user-form.ftl");
}
 
Example #6
Source File: OIDCLoginProtocol.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean isAuthTimeExpired(UserSessionModel userSession, AuthenticationSessionModel authSession) {
    String authTime = userSession.getNote(AuthenticationManager.AUTH_TIME);
    String maxAge = authSession.getClientNote(OIDCLoginProtocol.MAX_AGE_PARAM);
    if (maxAge == null) {
        return false;
    }

    int authTimeInt = authTime==null ? 0 : Integer.parseInt(authTime);
    int maxAgeInt = Integer.parseInt(maxAge);

    if (authTimeInt + maxAgeInt < Time.currentTime()) {
        logger.debugf("Authentication time is expired, needs to reauthenticate. userSession=%s, clientId=%s, maxAge=%d, authTime=%d", userSession.getId(),
                authSession.getClient().getId(), maxAgeInt, authTimeInt);
        return true;
    }

    return false;
}
 
Example #7
Source File: IdpUsernamePasswordForm.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected LoginFormsProvider setupForm(AuthenticationFlowContext context, MultivaluedMap<String, String> formData, Optional<UserModel> existingUser) {
    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }

    existingUser.ifPresent(u -> formData.putSingle(AuthenticationManager.FORM_USERNAME, u.getUsername()));

    LoginFormsProvider form = context.form()
            .setFormData(formData)
            .setAttribute(LoginFormsProvider.REGISTRATION_DISABLED, true)
            .setInfo(Messages.FEDERATED_IDENTITY_CONFIRM_REAUTHENTICATE_MESSAGE, serializedCtx.getIdentityProviderId());

    SerializedBrokeredIdentityContext serializedCtx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
    if (serializedCtx0 != null) {
        BrokeredIdentityContext ctx0 = serializedCtx0.deserialize(context.getSession(), context.getAuthenticationSession());
        form.setError(Messages.NESTED_FIRST_BROKER_FLOW_MESSAGE, ctx0.getIdpConfig().getAlias(), ctx0.getUsername());
        context.getAuthenticationSession().setAuthNote(AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT, null);
    }

    return form;
}
 
Example #8
Source File: UsernamePasswordForm.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> formData = new MultivaluedMapImpl<>();
    String loginHint = context.getAuthenticationSession().getClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM);

    String rememberMeUsername = AuthenticationManager.getRememberMeUsername(context.getRealm(), context.getHttpRequest().getHttpHeaders());

    if (loginHint != null || rememberMeUsername != null) {
        if (loginHint != null) {
            formData.add(AuthenticationManager.FORM_USERNAME, loginHint);
        } else {
            formData.add(AuthenticationManager.FORM_USERNAME, rememberMeUsername);
            formData.add("rememberMe", "on");
        }
    }
    Response challengeResponse = challenge(context, formData);
    context.challenge(challengeResponse);
}
 
Example #9
Source File: UserResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Revoke consent and offline tokens for particular client from user
 *
 * @param clientId Client id
 */
@Path("consents/{client}")
@DELETE
@NoCache
public void revokeConsent(final @PathParam("client") String clientId) {
    auth.users().requireManage(user);

    ClientModel client = realm.getClientByClientId(clientId);
    if (client == null) {
        throw new NotFoundException("Client not found");
    }
    boolean revokedConsent = session.users().revokeConsentForClient(realm, user.getId(), client.getId());
    boolean revokedOfflineToken = new UserSessionManager(session).revokeOfflineToken(user, client);

    if (revokedConsent) {
        // Logout clientSessions for this user and client
        AuthenticationManager.backchannelLogoutUserFromClient(session, realm, user, client, session.getContext().getUri(), headers);
    }

    if (!revokedConsent && !revokedOfflineToken) {
        throw new NotFoundException("Consent nor offline token not found");
    }
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
 
Example #10
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private Response registerRequest(String authSessionId, String code, String execution, String clientId, String tabId, boolean isPostRequest) {
    event.event(EventType.REGISTER);
    if (!realm.isRegistrationAllowed()) {
        event.error(Errors.REGISTRATION_DISABLED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REGISTRATION_NOT_ALLOWED);
    }

    SessionCodeChecks checks = checksForCode(authSessionId, code, execution, clientId, tabId, REGISTRATION_PATH);
    if (!checks.verifyActiveAndValidAction(AuthenticationSessionModel.Action.AUTHENTICATE.name(), ClientSessionCode.ActionType.LOGIN)) {
        return checks.getResponse();
    }

    AuthenticationSessionModel authSession = checks.getAuthenticationSession();

    processLocaleParam(authSession);

    AuthenticationManager.expireIdentityCookie(realm, session.getContext().getUri(), clientConnection);

    return processRegistration(checks.isActionRequest(), execution, authSession, null);
}
 
Example #11
Source File: SessionResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Remove sessions
 *
 * @param removeCurrent remove current session (default is false)
 * @return
 */
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response logout(@QueryParam("current") boolean removeCurrent) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    List<UserSessionModel> userSessions = session.sessions().getUserSessions(realm, user);

    for (UserSessionModel s : userSessions) {
        if (removeCurrent || !isCurrentSession(s)) {
            AuthenticationManager.backchannelLogout(session, s, true);
        }
    }

    return Cors.add(request, Response.noContent()).auth().allowedOrigins(auth.getToken()).build();
}
 
Example #12
Source File: CookieAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(context.getSession(),
            context.getRealm(), true);
    if (authResult == null) {
        context.attempted();
    } else {
        AuthenticationSessionModel clientSession = context.getAuthenticationSession();
        LoginProtocol protocol = context.getSession().getProvider(LoginProtocol.class, clientSession.getProtocol());

        // Cookie re-authentication is skipped if re-authentication is required
        if (protocol.requireReauthentication(authResult.getSession(), clientSession)) {
            context.attempted();
        } else {
            context.getSession().setAttribute(AuthenticationManager.SSO_AUTH, "true");

            context.setUser(authResult.getUser());
            context.attachUserSession(authResult.getSession());
            context.success();
        }
    }

}
 
Example #13
Source File: ClientScopeEvaluateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AccessToken generateToken(UserModel user, String scopeParam) {
    AuthenticationSessionModel authSession = null;
    UserSessionModel userSession = null;
    AuthenticationSessionManager authSessionManager = new AuthenticationSessionManager(session);

    try {
        RootAuthenticationSessionModel rootAuthSession = authSessionManager.createAuthenticationSession(realm, false);
        authSession = rootAuthSession.createAuthenticationSession(client);

        authSession.setAuthenticatedUser(user);
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()));
        authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scopeParam);

        userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, user, user.getUsername(),
                clientConnection.getRemoteAddr(), "example-auth", false, null, null);

        AuthenticationManager.setClientScopesInSession(authSession);
        ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);

        TokenManager tokenManager = new TokenManager();

        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, null, session, userSession, clientSessionCtx)
                .generateAccessToken();

        return responseBuilder.getAccessToken();

    } finally {
        if (authSession != null) {
            authSessionManager.removeAuthenticationSession(realm, authSession, false);
        }
        if (userSession != null) {
            session.sessions().removeUserSession(realm, userSession);
        }
    }
}
 
Example #14
Source File: AdminConsole.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Permission information
 *
 * @param headers
 * @return
 */
@Path("whoami")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response whoAmI(final @Context HttpHeaders headers) {
    RealmManager realmManager = new RealmManager(session);
    AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers);
    if (authResult == null) {
        return Response.status(401).build();
    }
    UserModel user= authResult.getUser();
    String displayName;
    if ((user.getFirstName() != null && !user.getFirstName().trim().equals("")) || (user.getLastName() != null && !user.getLastName().trim().equals(""))) {
        displayName = user.getFirstName();
        if (user.getLastName() != null) {
            displayName = displayName != null ? displayName + " " + user.getLastName() : user.getLastName();
        }
    } else {
        displayName = user.getUsername();
    }

    RealmModel masterRealm = getAdminstrationRealm(realmManager);
    Map<String, Set<String>> realmAccess = new HashMap<String, Set<String>>();
    if (masterRealm == null)
        throw new NotFoundException("No realm found");
    boolean createRealm = false;
    if (realm.equals(masterRealm)) {
        logger.debug("setting up realm access for a master realm user");
        createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM));
        addMasterRealmAccess(realm, user, realmAccess);
    } else {
        logger.debug("setting up realm access for a realm user");
        addRealmAccess(realm, user, realmAccess);
    }

    Locale locale = session.getContext().resolveLocale(user);

    return Response.ok(new WhoAmI(user.getId(), realm.getName(), displayName, createRealm, realmAccess, locale)).build();
}
 
Example #15
Source File: AdminRoot.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
    String tokenString = authManager.extractAuthorizationHeaderToken(headers);
    if (tokenString == null) throw new NotAuthorizedException("Bearer");
    AccessToken token;
    try {
        JWSInput input = new JWSInput(tokenString);
        token = input.readJsonContent(AccessToken.class);
    } catch (JWSInputException e) {
        throw new NotAuthorizedException("Bearer token format error");
    }
    String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        throw new NotAuthorizedException("Unknown realm in token");
    }
    session.getContext().setRealm(realm);
    AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers);
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }

    ClientModel client = realm.getClientByClientId(token.getIssuedFor());
    if (client == null) {
        throw new NotFoundException("Could not find client for authorization");

    }

    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);
}
 
Example #16
Source File: PasswordAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
protected Response challenge(AuthenticationFlowContext context, String error) {

    LoginFormsProvider form = context.form();

    if (error != null) {
        form.setError(error);
    }

    String attemptedUsername = context.getAuthenticationSession().getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);
    form.setAttribute(AuthenticationManager.FORM_USERNAME, attemptedUsername);

    Response response = form.createForm("validate-password-form.ftl");
    return response;
}
 
Example #17
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private boolean validateUsernameForm(AuthenticationFlowContext context, MultivaluedMap<String, String> inputData) {

        String username = inputData.getFirst(AuthenticationManager.FORM_USERNAME);
        if (username == null) {
            failWithUserNotFound(context);
            return false;
        }

        // remove leading and trailing whitespace
        username = username.trim();

        context.getEvent().detail(Details.USERNAME, username);
        context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

        UserModel user = lookupUser(context, username);

        if (user == null) {
            testInvalidUser(context, user);
            return false;
        }

        if (!enabledUser(context, user)) {
            return false;
        }

        String rememberMe = inputData.getFirst("rememberMe");
        boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on");
        if (remember) {
            context.getAuthenticationSession().setAuthNote(Details.REMEMBER_ME, "true");
            context.getEvent().detail(Details.REMEMBER_ME, "true");
        } else {
            context.getAuthenticationSession().removeAuthNote(Details.REMEMBER_ME);
        }
        context.setUser(user);
        return true;
    }
 
Example #18
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response finishBrokerAuthentication(BrokeredIdentityContext context, UserModel federatedUser, AuthenticationSessionModel authSession, String providerId) {
    authSession.setAuthNote(AuthenticationProcessor.BROKER_SESSION_ID, context.getBrokerSessionId());
    authSession.setAuthNote(AuthenticationProcessor.BROKER_USER_ID, context.getBrokerUserId());

    this.event.user(federatedUser);

    context.getIdp().authenticationFinished(authSession, context);
    authSession.setUserSessionNote(Details.IDENTITY_PROVIDER, providerId);
    authSession.setUserSessionNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

    event.detail(Details.IDENTITY_PROVIDER, providerId)
            .detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

    if (isDebugEnabled()) {
        logger.debugf("Performing local authentication for user [%s].", federatedUser);
    }

    AuthenticationManager.setClientScopesInSession(authSession);

    String nextRequiredAction = AuthenticationManager.nextRequiredAction(session, authSession, clientConnection, request, session.getContext().getUri(), event);
    if (nextRequiredAction != null) {
        if ("true".equals(authSession.getAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN))) {
            logger.errorf("Required action %s found. Auth requests using prompt=none are incompatible with required actions", nextRequiredAction);
            return checkPassiveLoginError(authSession, OAuthErrorException.INTERACTION_REQUIRED);
        }
        return AuthenticationManager.redirectToRequiredActions(session, realmModel, authSession, session.getContext().getUri(), nextRequiredAction);
    } else {
        event.detail(Details.CODE_ID, authSession.getParentSession().getId());  // todo This should be set elsewhere.  find out why tests fail.  Don't know where this is supposed to be set
        return AuthenticationManager.finishedRequiredActions(session, authSession, null, clientConnection, request, session.getContext().getUri(), event);
    }
}
 
Example #19
Source File: SessionResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a specific session
 *
 * @param id a specific session to remove
 * @return
 */
@Path("/{id}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response logout(@PathParam("id") String id) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    UserSessionModel userSession = session.sessions().getUserSession(realm, id);
    if (userSession != null && userSession.getUser().equals(user)) {
        AuthenticationManager.backchannelLogout(session, userSession, true);
    }
    return Cors.add(request, Response.noContent()).auth().allowedOrigins(auth.getToken()).build();
}
 
Example #20
Source File: AccountFormService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("sessions")
@POST
public Response processSessionsLogout(final MultivaluedMap<String, String> formData) {
    if (auth == null) {
        return login("sessions");
    }

    auth.require(AccountRoles.MANAGE_ACCOUNT);
    csrfCheck(formData);

    UserModel user = auth.getUser();

    // Rather decrease time a bit. To avoid situation when user is immediatelly redirected to login screen, then automatically authenticated (eg. with Kerberos) and then seeing issues due the stale token
    // as time on the token will be same like notBefore
    session.users().setNotBeforeForUser(realm, user, Time.currentTime() - 1);

    List<UserSessionModel> userSessions = session.sessions().getUserSessions(realm, user);
    for (UserSessionModel userSession : userSessions) {
        AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, true);
    }

    UriBuilder builder = Urls.accountBase(session.getContext().getUri().getBaseUri()).path(AccountFormService.class, "sessionsPage");
    String referrer = session.getContext().getUri().getQueryParameters().getFirst("referrer");
    if (referrer != null) {
        builder.queryParam("referrer", referrer);

    }
    URI location = builder.build(realm.getName());
    return Response.seeOther(location).build();
}
 
Example #21
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(JsonWebToken t) throws VerificationException {
    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    if (authSession != null && ! Objects.equals(authSession.getAction(), this.expectedAction.name())) {
        if (Objects.equals(AuthenticationSessionModel.Action.REQUIRED_ACTIONS.name(), authSession.getAction())) {
            throw new LoginActionsServiceException(
              AuthenticationManager.nextActionAfterAuthentication(context.getSession(), authSession,
                context.getClientConnection(), context.getRequest(), context.getUriInfo(), context.getEvent()));
        }
        throw new ExplainedTokenVerificationException(t, Errors.INVALID_TOKEN, Messages.INVALID_CODE);
    }

    return true;
}
 
Example #22
Source File: RealmAdminResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a specific user session. Any client that has an admin url will also be told to invalidate this
 * particular session.
 *
 * @param sessionId
 */
@Path("sessions/{session}")
@DELETE
public void deleteSession(@PathParam("session") String sessionId) {
    auth.users().requireManage();

    UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
    if (userSession == null) throw new NotFoundException("Sesssion not found");
    AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), connection, headers, true);
    adminEvent.operation(OperationType.DELETE).resource(ResourceType.USER_SESSION).resourcePath(session.getContext().getUri()).success();

}
 
Example #23
Source File: DefaultLocaleUpdaterProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void expireLocaleCookie() {
    RealmModel realm = session.getContext().getRealm();
    UriInfo uriInfo = session.getContext().getUri();

    boolean secure = realm.getSslRequired().isRequired(session.getContext().getConnection());
    CookieHelper.addCookie(LocaleSelectorProvider.LOCALE_COOKIE, "", AuthenticationManager.getRealmCookiePath(realm, uriInfo), null, "Expiring cookie", 0, secure, true);
}
 
Example #24
Source File: DefaultLocaleUpdaterProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void updateLocaleCookie(String locale) {
    RealmModel realm = session.getContext().getRealm();
    UriInfo uriInfo = session.getContext().getUri();

    boolean secure = realm.getSslRequired().isRequired(uriInfo.getRequestUri().getHost());
    CookieHelper.addCookie(LocaleSelectorProvider.LOCALE_COOKIE, locale, AuthenticationManager.getRealmCookiePath(realm, uriInfo), null, null, -1, secure, true);
    logger.debugv("Updating locale cookie to {0}", locale);
}
 
Example #25
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Response authenticationComplete() {
    // attachSession(); // Session will be attached after requiredActions + consents are finished.
    AuthenticationManager.setClientScopesInSession(authenticationSession);

    String nextRequiredAction = nextRequiredAction();
    if (nextRequiredAction != null) {
        return AuthenticationManager.redirectToRequiredActions(session, realm, authenticationSession, uriInfo, nextRequiredAction);
    } else {
        event.detail(Details.CODE_ID, authenticationSession.getParentSession().getId());  // todo This should be set elsewhere.  find out why tests fail.  Don't know where this is supposed to be set
        return AuthenticationManager.finishedRequiredActions(session, authenticationSession, userSession, connection, request, uriInfo, event);
    }
}
 
Example #26
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Response finishAuthentication(LoginProtocol protocol) {
    RealmModel realm = authenticationSession.getRealm();
    ClientSessionContext clientSessionCtx = attachSession();
    event.success();
    return AuthenticationManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, connection, event, authenticationSession, protocol);

}
 
Example #27
Source File: ExportResourceProvider.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This code has been copied from keycloak org.keycloak.services.resources.admin.AdminRoot;
 * it allows to check if a user as realm/master admin
 * at each upgrade check that it hasn't been modified
 */
private AdminAuth authenticateRealmAdminRequest(HttpHeaders headers, UriInfo uriInfo) {
    String tokenString = authManager.extractAuthorizationHeaderToken(headers);
    if (tokenString == null) throw new NotAuthorizedException("Bearer");
    AccessToken token;
    try {
        JWSInput input = new JWSInput(tokenString);
        token = input.readJsonContent(AccessToken.class);
    } catch (JWSInputException e) {
        throw new NotAuthorizedException("Bearer token format error", e);
    }
    String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        throw new NotAuthorizedException("Unknown realm in token");
    }
    session.getContext().setRealm(realm);
    AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, uriInfo, clientConnection, headers);
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }

    ClientModel client = realm.getClientByClientId(token.getIssuedFor());
    if (client == null) {
        throw new NotFoundException("Could not find client for authorization");

    }

    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);
}
 
Example #28
Source File: AbstractUsernameFormAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserModel getUser(AuthenticationFlowContext context, MultivaluedMap<String, String> inputData) {
    String username = inputData.getFirst(AuthenticationManager.FORM_USERNAME);
    if (username == null) {
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = challenge(context, getDefaultChallengeMessage(context));
        context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return null;
    }

    // remove leading and trailing whitespace
    username = username.trim();

    context.getEvent().detail(Details.USERNAME, username);
    context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

    UserModel user = null;
    try {
        user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    } catch (ModelDuplicateException mde) {
        ServicesLogger.LOGGER.modelDuplicateException(mde);

        // Could happen during federation import
        if (mde.getDuplicateFieldName() != null && mde.getDuplicateFieldName().equals(UserModel.EMAIL)) {
            setDuplicateUserChallenge(context, Errors.EMAIL_IN_USE, Messages.EMAIL_EXISTS, AuthenticationFlowError.INVALID_USER);
        } else {
            setDuplicateUserChallenge(context, Errors.USERNAME_IN_USE, Messages.USERNAME_EXISTS, AuthenticationFlowError.INVALID_USER);
        }
        return user;
    }

    testInvalidUser(context, user);
    return user;
}
 
Example #29
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void logFailure() {
    if (realm.isBruteForceProtected()) {
        UserModel user = AuthenticationManager.lookupUserForBruteForceLog(session, realm, authenticationSession);
        if (user != null) {
            getBruteForceProtector().failedLogin(realm, user, connection);
        }
    }
}
 
Example #30
Source File: BasicAuthAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected boolean checkUsernameAndPassword(AuthenticationFlowContext context, String username, String password) {
    MultivaluedMap<String, String> map = new MultivaluedHashMap<>();

    map.putSingle(AuthenticationManager.FORM_USERNAME, username);
    map.putSingle(CredentialRepresentation.PASSWORD, password);

    if (validateUserAndPassword(context, map)) {
        return true;
    }

    return false;
}