@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);
    }
  }
Example #2
0
  public static void attachClientSession(
      UserSessionModel session, ClientSessionModel clientSession) {
    if (clientSession.getUserSession() != null) {
      return;
    }

    UserModel user = session.getUser();
    clientSession.setUserSession(session);
    Set<String> requestedRoles = new HashSet<String>();
    // todo scope param protocol independent
    for (RoleModel r : TokenManager.getAccess(null, clientSession.getClient(), user)) {
      requestedRoles.add(r.getId());
    }
    clientSession.setRoles(requestedRoles);

    Set<String> requestedProtocolMappers = new HashSet<String>();
    for (ProtocolMapperModel protocolMapper : clientSession.getClient().getProtocolMappers()) {
      if (protocolMapper.getProtocol().equals(clientSession.getAuthMethod())) {
        requestedProtocolMappers.add(protocolMapper.getId());
      }
    }
    clientSession.setProtocolMappers(requestedProtocolMappers);

    Map<String, String> transferredNotes = clientSession.getUserSessionNotes();
    for (Map.Entry<String, String> entry : transferredNotes.entrySet()) {
      session.setNote(entry.getKey(), entry.getValue());
    }
  }
Example #3
0
 protected String getNameId(
     String nameIdFormat, ClientSessionModel clientSession, UserSessionModel userSession) {
   if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.get())) {
     return userSession.getUser().getEmail();
   } else if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_TRANSIENT.get())) {
     // "G-" stands for "generated" Add this for the slight possibility of collisions.
     return "G-" + UUID.randomUUID().toString();
   } else if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get())) {
     return getPersistentNameId(clientSession, userSession);
   } else if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.get())) {
     // TODO: Support for persistent NameID (pseudo-random identifier persisted in user object)
     return userSession.getUser().getUsername();
   } else {
     return userSession.getUser().getUsername();
   }
 }
Example #4
0
  /**
   * Impersonate the user
   *
   * @param id User id
   * @return
   */
  @Path("{id}/impersonation")
  @POST
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public Map<String, Object> impersonate(final @PathParam("id") String id) {
    auth.init(RealmAuth.Resource.IMPERSONATION);
    auth.requireManage();
    UserModel user = session.users().getUserById(id, realm);
    if (user == null) {
      throw new NotFoundException("User not found");
    }
    RealmModel authenticatedRealm = auth.getAuth().getRealm();
    // if same realm logout before impersonation
    boolean sameRealm = false;
    if (authenticatedRealm.getId().equals(realm.getId())) {
      sameRealm = true;
      UserSessionModel userSession =
          session
              .sessions()
              .getUserSession(authenticatedRealm, auth.getAuth().getToken().getSessionState());
      AuthenticationManager.expireIdentityCookie(realm, uriInfo, clientConnection);
      AuthenticationManager.expireRememberMeCookie(realm, uriInfo, clientConnection);
      AuthenticationManager.backchannelLogout(
          session, authenticatedRealm, userSession, uriInfo, clientConnection, headers, true);
    }
    EventBuilder event = new EventBuilder(realm, session, clientConnection);

    UserSessionModel userSession =
        session
            .sessions()
            .createUserSession(
                realm,
                user,
                user.getUsername(),
                clientConnection.getRemoteAddr(),
                "impersonate",
                false,
                null,
                null);
    AuthenticationManager.createLoginCookie(
        realm, userSession.getUser(), userSession, uriInfo, clientConnection);
    URI redirect = AccountService.accountServiceApplicationPage(uriInfo).build(realm.getName());
    Map<String, Object> result = new HashMap<>();
    result.put("sameRealm", sameRealm);
    result.put("redirect", redirect.toString());
    event
        .event(EventType.IMPERSONATE)
        .session(userSession)
        .user(user)
        .detail(Details.IMPERSONATOR_REALM, authenticatedRealm.getName())
        .detail(Details.IMPERSONATOR, auth.getAuth().getUser().getUsername())
        .success();

    return result;
  }
 @Override
 public void transformAttributeStatement(
     AttributeStatementType attributeStatement,
     ProtocolMapperModel mappingModel,
     KeycloakSession session,
     UserSessionModel userSession,
     ClientSessionModel clientSession) {
   UserModel user = userSession.getUser();
   String attributeName = mappingModel.getConfig().get(ProtocolMapperUtils.USER_ATTRIBUTE);
   String attributeValue = user.getFirstAttribute(attributeName);
   if (attributeValue == null) return;
   AttributeStatementHelper.addAttribute(attributeStatement, mappingModel, attributeValue);
 }
Example #6
0
  @Override
  public Response finishLogout(UserSessionModel userSession) {
    String redirectUri = userSession.getNote(OIDCLoginProtocol.LOGOUT_REDIRECT_URI);
    String state = userSession.getNote(OIDCLoginProtocol.LOGOUT_STATE_PARAM);
    event.event(EventType.LOGOUT);
    if (redirectUri != null) {
      event.detail(Details.REDIRECT_URI, redirectUri);
    }
    event.user(userSession.getUser()).session(userSession).success();

    if (redirectUri != null) {
      UriBuilder uriBuilder = UriBuilder.fromUri(redirectUri);
      if (state != null) uriBuilder.queryParam(STATE_PARAM, state);
      return Response.status(302).location(uriBuilder.build()).build();
    } else {
      return Response.ok().build();
    }
  }
Example #7
0
 public AccessTokenResponseBuilder generateIDToken() {
   if (accessToken == null) {
     throw new IllegalStateException("accessToken not set");
   }
   idToken = new IDToken();
   idToken.id(KeycloakModelUtils.generateId());
   idToken.subject(accessToken.getSubject());
   idToken.audience(client.getClientId());
   idToken.issuedNow();
   idToken.issuedFor(accessToken.getIssuedFor());
   idToken.issuer(accessToken.getIssuer());
   idToken.setSessionState(accessToken.getSessionState());
   if (realm.getAccessTokenLifespan() > 0) {
     idToken.expiration(Time.currentTime() + realm.getAccessTokenLifespan());
   }
   transformIDToken(
       session, idToken, realm, client, userSession.getUser(), userSession, clientSession);
   return this;
 }
Example #8
0
  /**
   * Attempts to retrieve the persistent type NameId as follows:
   *
   * <ol>
   *   <li>saml.persistent.name.id.for.$clientId user attribute
   *   <li>saml.persistent.name.id.for.* user attribute
   *   <li>G-$randomUuid
   * </ol>
   *
   * If a randomUuid is generated, an attribute for the given saml.persistent.name.id.for.$clientId
   * will be generated, otherwise no state change will occur with respect to the user's attributes.
   *
   * @return the user's persistent NameId
   */
  protected String getPersistentNameId(
      final ClientSessionModel clientSession, final UserSessionModel userSession) {
    // attempt to retrieve the UserID for the client-specific attribute
    final UserModel user = userSession.getUser();
    final String clientNameId =
        String.format(
            "%s.%s", SAML_PERSISTENT_NAME_ID_FOR, clientSession.getClient().getClientId());
    String samlPersistentNameId = user.getFirstAttribute(clientNameId);
    if (samlPersistentNameId != null) {
      return samlPersistentNameId;
    }

    // check for a wildcard attribute
    final String wildcardNameId = String.format("%s.*", SAML_PERSISTENT_NAME_ID_FOR);
    samlPersistentNameId = user.getFirstAttribute(wildcardNameId);
    if (samlPersistentNameId != null) {
      return samlPersistentNameId;
    }

    // default to generated.  "G-" stands for "generated"
    samlPersistentNameId = "G-" + UUID.randomUUID().toString();
    user.setSingleAttribute(clientNameId, samlPersistentNameId);
    return samlPersistentNameId;
  }
  /**
   * OAuth grant page. You should not invoked this directly!
   *
   * @param formData
   * @return
   */
  @Path("consent")
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public Response processConsent(final MultivaluedMap<String, String> formData) {
    event.event(EventType.LOGIN).detail(Details.RESPONSE_TYPE, "code");

    if (!checkSsl()) {
      return ErrorPage.error(session, Messages.HTTPS_REQUIRED);
    }

    String code = formData.getFirst("code");

    ClientSessionCode accessCode = ClientSessionCode.parse(code, session, realm);
    if (accessCode == null || !accessCode.isValid(ClientSessionModel.Action.OAUTH_GRANT.name())) {
      event.error(Errors.INVALID_CODE);
      return ErrorPage.error(session, Messages.INVALID_ACCESS_CODE);
    }
    ClientSessionModel clientSession = accessCode.getClientSession();
    event.detail(Details.CODE_ID, clientSession.getId());

    String redirect = clientSession.getRedirectUri();
    UserSessionModel userSession = clientSession.getUserSession();
    UserModel user = userSession.getUser();
    ClientModel client = clientSession.getClient();

    event
        .client(client)
        .user(user)
        .detail(Details.RESPONSE_TYPE, "code")
        .detail(Details.REDIRECT_URI, redirect);

    event.detail(Details.AUTH_METHOD, userSession.getAuthMethod());
    event.detail(Details.USERNAME, userSession.getLoginUsername());
    if (userSession.isRememberMe()) {
      event.detail(Details.REMEMBER_ME, "true");
    }

    if (!AuthenticationManager.isSessionValid(realm, userSession)) {
      AuthenticationManager.backchannelLogout(
          session, realm, userSession, uriInfo, clientConnection, headers, true);
      event.error(Errors.INVALID_CODE);
      return ErrorPage.error(session, Messages.SESSION_NOT_ACTIVE);
    }
    event.session(userSession);

    if (formData.containsKey("cancel")) {
      LoginProtocol protocol =
          session.getProvider(LoginProtocol.class, clientSession.getAuthMethod());
      protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(uriInfo);
      event.error(Errors.REJECTED_BY_USER);
      return protocol.consentDenied(clientSession);
    }

    UserConsentModel grantedConsent = user.getConsentByClient(client.getId());
    if (grantedConsent == null) {
      grantedConsent = new UserConsentModel(client);
      user.addConsent(grantedConsent);
    }
    for (RoleModel role : accessCode.getRequestedRoles()) {
      grantedConsent.addGrantedRole(role);
    }
    for (ProtocolMapperModel protocolMapper : accessCode.getRequestedProtocolMappers()) {
      if (protocolMapper.isConsentRequired() && protocolMapper.getConsentText() != null) {
        grantedConsent.addGrantedProtocolMapper(protocolMapper);
      }
    }
    user.updateConsent(grantedConsent);

    event.detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED);
    event.success();

    return authManager.redirectAfterSuccessfulFlow(
        session, realm, userSession, clientSession, request, uriInfo, clientConnection);
  }