예제 #1
0
  @Path("email-verification")
  @GET
  public Response emailVerification(
      @QueryParam("code") String code, @QueryParam("key") String key) {
    event.event(EventType.VERIFY_EMAIL);
    if (key != null) {
      Checks checks = new Checks();
      if (!checks.verifyCode(key, ClientSessionModel.Action.VERIFY_EMAIL.name())) {
        return checks.response;
      }
      ClientSessionCode accessCode = checks.clientCode;
      ClientSessionModel clientSession = accessCode.getClientSession();
      UserSessionModel userSession = clientSession.getUserSession();
      UserModel user = userSession.getUser();
      initEvent(clientSession);
      user.setEmailVerified(true);

      user.removeRequiredAction(RequiredAction.VERIFY_EMAIL);

      event.event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, user.getEmail()).success();

      String actionCookieValue = getActionCookie();
      if (actionCookieValue == null || !actionCookieValue.equals(userSession.getId())) {
        session.sessions().removeClientSession(realm, clientSession);
        return session
            .getProvider(LoginFormsProvider.class)
            .setSuccess(Messages.EMAIL_VERIFIED)
            .createInfoPage();
      }

      event = event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN);

      return AuthenticationManager.nextActionAfterAuthentication(
          session, userSession, clientSession, clientConnection, request, uriInfo, event);
    } else {
      Checks checks = new Checks();
      if (!checks.verifyCode(code, ClientSessionModel.Action.VERIFY_EMAIL.name())) {
        return checks.response;
      }
      ClientSessionCode accessCode = checks.clientCode;
      ClientSessionModel clientSession = accessCode.getClientSession();
      UserSessionModel userSession = clientSession.getUserSession();
      initEvent(clientSession);

      createActionCookie(realm, uriInfo, clientConnection, userSession.getId());

      return session
          .getProvider(LoginFormsProvider.class)
          .setClientSessionCode(accessCode.getCode())
          .setUser(userSession.getUser())
          .createResponse(RequiredAction.VERIFY_EMAIL);
    }
  }
예제 #2
0
 @Override
 public Response keycloakInitiatedBrowserLogout(
     UserSessionModel userSession, UriInfo uriInfo, RealmModel realm) {
   if (getConfig().getLogoutUrl() == null || getConfig().getLogoutUrl().trim().equals(""))
     return null;
   String idToken = userSession.getNote(FEDERATED_ID_TOKEN);
   if (idToken != null && getConfig().isBackchannelSupported()) {
     backchannelLogout(userSession, idToken);
     return null;
   } else {
     String sessionId = userSession.getId();
     UriBuilder logoutUri =
         UriBuilder.fromUri(getConfig().getLogoutUrl()).queryParam("state", sessionId);
     if (idToken != null) logoutUri.queryParam("id_token_hint", idToken);
     String redirect =
         RealmsResource.brokerUrl(uriInfo)
             .path(IdentityBrokerService.class, "getEndpoint")
             .path(OIDCEndpoint.class, "logoutResponse")
             .build(realm.getName(), getConfig().getAlias())
             .toString();
     logoutUri.queryParam("post_logout_redirect_uri", redirect);
     Response response = Response.status(302).location(logoutUri.build()).build();
     return response;
   }
 }
예제 #3
0
 protected AccessToken initToken(
     RealmModel realm,
     ClientModel client,
     UserModel user,
     UserSessionModel session,
     ClientSessionModel clientSession) {
   AccessToken token = new AccessToken();
   if (clientSession != null) token.clientSession(clientSession.getId());
   token.id(KeycloakModelUtils.generateId());
   token.subject(user.getId());
   token.audience(client.getClientId());
   token.issuedNow();
   token.issuedFor(client.getClientId());
   token.issuer(clientSession.getNote(OIDCLoginProtocol.ISSUER));
   if (session != null) {
     token.setSessionState(session.getId());
   }
   if (realm.getAccessTokenLifespan() > 0) {
     token.expiration(Time.currentTime() + realm.getAccessTokenLifespan());
   }
   Set<String> allowedOrigins = client.getWebOrigins();
   if (allowedOrigins != null) {
     token.setAllowedOrigins(allowedOrigins);
   }
   return token;
 }
예제 #4
0
 @Path("sessions/{session}")
 @DELETE
 public void deleteSession(@PathParam("session") String sessionId) {
   UserSessionModel session = realm.getUserSession(sessionId);
   if (session == null) throw new NotFoundException("Sesssion not found");
   realm.removeUserSession(session);
   new ResourceAdminManager().logoutSession(uriInfo.getRequestUri(), realm, session.getId());
 }
예제 #5
0
 protected void backchannelLogout(UserSessionModel userSession, String idToken) {
   String sessionId = userSession.getId();
   UriBuilder logoutUri =
       UriBuilder.fromUri(getConfig().getLogoutUrl()).queryParam("state", sessionId);
   logoutUri.queryParam("id_token_hint", idToken);
   String url = logoutUri.build().toString();
   try {
     int status = JsonSimpleHttp.doGet(url).asStatus();
     boolean success = status >= 200 && status < 400;
     if (!success) {
       logger.warn("Failed backchannel broker logout to: " + url);
     }
   } catch (Exception e) {
     logger.warn("Failed backchannel broker logout to: " + url, e);
   }
 }
예제 #6
0
  /**
   * Update account password
   *
   * <p>Form params:
   *
   * <p>password - old password password-new pasword-confirm
   *
   * @param formData
   * @return
   */
  @Path("password")
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public Response processPasswordUpdate(final MultivaluedMap<String, String> formData) {
    if (auth == null) {
      return login("password");
    }

    require(AccountRoles.MANAGE_ACCOUNT);

    String action = formData.getFirst("submitAction");
    if (action != null && action.equals("Cancel")) {
      setReferrerOnPage();
      return account.createResponse(AccountPages.PASSWORD);
    }

    csrfCheck(formData);
    UserModel user = auth.getUser();

    boolean requireCurrent = isPasswordSet(user);
    account.setPasswordSet(requireCurrent);

    String password = formData.getFirst("password");
    String passwordNew = formData.getFirst("password-new");
    String passwordConfirm = formData.getFirst("password-confirm");

    if (requireCurrent) {
      if (Validation.isBlank(password)) {
        setReferrerOnPage();
        return account.setError(Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
      }

      UserCredentialModel cred = UserCredentialModel.password(password);
      if (!session.users().validCredentials(realm, user, cred)) {
        setReferrerOnPage();
        return account
            .setError(Messages.INVALID_PASSWORD_EXISTING)
            .createResponse(AccountPages.PASSWORD);
      }
    }

    if (Validation.isEmpty(passwordNew)) {
      setReferrerOnPage();
      return account.setError(Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
    }

    if (!passwordNew.equals(passwordConfirm)) {
      setReferrerOnPage();
      return account
          .setError(Messages.INVALID_PASSWORD_CONFIRM)
          .createResponse(AccountPages.PASSWORD);
    }

    try {
      session.users().updateCredential(realm, user, UserCredentialModel.password(passwordNew));
    } catch (ModelReadOnlyException mre) {
      setReferrerOnPage();
      return account.setError(Messages.READ_ONLY_PASSWORD).createResponse(AccountPages.PASSWORD);
    } catch (ModelException me) {
      logger.error("Failed to update password", me);
      setReferrerOnPage();
      return account
          .setError(me.getMessage(), me.getParameters())
          .createResponse(AccountPages.PASSWORD);
    } catch (Exception ape) {
      logger.error("Failed to update password", ape);
      setReferrerOnPage();
      return account.setError(ape.getMessage()).createResponse(AccountPages.PASSWORD);
    }

    List<UserSessionModel> sessions = session.sessions().getUserSessions(realm, user);
    for (UserSessionModel s : sessions) {
      if (!s.getId().equals(auth.getSession().getId())) {
        AuthenticationManager.backchannelLogout(
            session, realm, s, uriInfo, clientConnection, headers, true);
      }
    }

    event.event(EventType.UPDATE_PASSWORD).client(auth.getClient()).user(auth.getUser()).success();

    setReferrerOnPage();
    return account
        .setPasswordSet(true)
        .setSuccess(Messages.ACCOUNT_PASSWORD_UPDATED)
        .createResponse(AccountPages.PASSWORD);
  }