---
source_url: "https://github.com/devondragon/SpringUserFramework?utm_source=openai"
title: "GitHub - devondragon/SpringUserFramework: Easy User Management Framework/Starter App for Spring. Providing registration, login, logout, and more built on top of Spring Security. · GitHub"
mirrored_at: 2026-08-11T01:02:01.795Z
host: github.com
cited_in_42a: true
mirror_canonical: "https://index.42a.ai/github.com/devondragon/SpringUserFramework__q__utm_source_openai"
---

> **Original source:** https://github.com/devondragon/SpringUserFramework?utm_source=openai

    

A comprehensive Spring Boot User Management Framework that simplifies the implementation of robust user authentication and management features. Built on top of Spring Security, this library provides ready-to-use solutions for user registration, login, account management, and more.

Check out the [Spring User Framework Demo Application](https://github.com/devondragon/SpringUserFrameworkDemoApp) for a complete example of how to use this library.

## Table of Contents

-   [Spring User Framework](#spring-user-framework)
    -   [Table of Contents](#table-of-contents)
    -   [Features](#features)
    -   [Installation](#installation)
        -   [Spring Boot 4.x (Latest)](#spring-boot-4x-latest)
            -   [Spring Boot 4.x Key Changes](#spring-boot-4x-key-changes)
        -   [Spring Boot 3.5 (Stable)](#spring-boot-35-stable)
    -   [Migration Guide](#migration-guide)
    -   [Quick Start](#quick-start)
        -   [Prerequisites](#prerequisites)
        -   [Step 1: Add Dependencies](#step-1-add-dependencies)
        -   [Step 2: Database Configuration](#step-2-database-configuration)
        -   [Step 3: JPA Configuration](#step-3-jpa-configuration)
        -   [Step 4: Email Configuration (Optional but Recommended)](#step-4-email-configuration-optional-but-recommended)
        -   [Step 5: Essential Framework Configuration](#step-5-essential-framework-configuration)
        -   [Step 6: Create User Profile Extension (Optional)](#step-6-create-user-profile-extension-optional)
        -   [Step 7: Start Your Application](#step-7-start-your-application)
        -   [Step 8: Test Core Features](#step-8-test-core-features)
        -   [Step 9: Customize Pages (Required for user-facing pages)](#step-9-customize-pages-required-for-user-facing-pages)
        -   [Complete Example Configuration](#complete-example-configuration)
        -   [Next Steps](#next-steps)
    -   [Configuration](#configuration)
    -   [Security Features](#security-features)
        -   [Role-Based Access Control](#role-based-access-control)
        -   [Account Lockout](#account-lockout)
        -   [Audit Logging](#audit-logging)
        -   [HTMX Support](#htmx-support)
    -   [User Management](#user-management)
        -   [Registration](#registration)
        -   [Profile Management](#profile-management)
        -   [Admin Password Reset](#admin-password-reset)
    -   [Email Verification](#email-verification)
    -   [Authentication](#authentication)
        -   [Local Authentication](#local-authentication)
        -   [WebAuthn / Passkeys](#webauthn--passkeys)
        -   [OAuth2/SSO](#oauth2sso)
            -   [**SSO OIDC with Keycloak**](#sso-oidc-with-keycloak)
    -   [Extensibility](#extensibility)
        -   [Custom User Profiles](#custom-user-profiles)
        -   [Handling User Account Deletion and Profile Cleanup](#handling-user-account-deletion-and-profile-cleanup)
            -   [Enabling Actual Deletion](#enabling-actual-deletion)
        -   [SSO OAuth2 with Google and Facebook](#sso-oauth2-with-google-and-facebook)
    -   [GDPR Compliance](#gdpr-compliance)
        -   [Enabling GDPR Features](#enabling-gdpr-features)
        -   [Data Export (Right of Access)](#data-export-right-of-access)
        -   [Account Deletion (Right to be Forgotten)](#account-deletion-right-to-be-forgotten)
        -   [Consent Management](#consent-management)
        -   [Extending GDPR Exports](#extending-gdpr-exports)
        -   [GDPR Events](#gdpr-events)
    -   [Examples](#examples)
    -   [Contributing](#contributing)
    -   [Reference Documentation](#reference-documentation)
    -   [License](#license)

## Features

-   **User Registration and Authentication**
    
    -   Registration, with optional email verification.
    -   Login and logout functionality.
    -   Forgot password flow.
    -   Admin-initiated password reset with optional session invalidation.
    -   Database-backed user store using Spring JPA.
    -   SSO support for Google
    -   SSO support for Facebook
    -   SSO support for Keycloak
    -   WebAuthn/Passkey support for passwordless login (biometrics, security keys, device authentication)
    -   Configuration options to control anonymous access, whitelist URIs, and protect specific URIs requiring a logged-in user session.
    -   CSRF protection enabled by default, with example jQuery AJAX calls passing the CSRF token from the Thymeleaf page context.
    -   Audit event framework for recording and logging security events, customizable to store audit events in a database or publish them via a REST API.
    -   Role and Privilege setup service to define roles, associated privileges, and role inheritance hierarchy using `application.yml`.
    -   Configurable Account Lockout after too many failed login attempts
    -   HTMX-aware session expiry handling — returns 401 JSON instead of 302 redirect for HTMX requests, preventing broken UI fragments
-   **Advanced Security**
    
    -   Role and privilege-based authorization
    -   Configurable password policies
    -   Account lockout after failed login attempts
    -   Audit logging for security events
    -   CSRF protection out of the box
    -   WebAuthn/Passkey credential management (register, rename, delete)
-   **Extensible Architecture**
    
    -   Easily extend user profiles with custom data
    -   Override default behaviors where needed
    -   Integration with Spring ecosystem
    -   Customizable UI templates
-   **Developer-Friendly**
    
    -   Minimal boilerplate code to get started
    -   Configuration-driven features
    -   Comprehensive documentation
    -   Demo application for reference
    -   Built-in dev login controller for quick user switching during local development
-   **GDPR Compliance** (opt-in)
    
    -   Data export (Right of Access - Article 15)
    -   Account deletion (Right to be Forgotten - Article 17)
    -   Consent tracking and management (Article 7)
    -   Extensible data contributor system for custom data
    -   Audit trail for all GDPR operations

## Installation

Choose the version that matches your Spring Boot version:

Spring Boot Version

Framework Version

Java Version

Spring Security

4.0.x – 4.1.x

5.1.x

21+

7.x

3.5.x

3.6.x

17+

6.x

> **Versioning note:** This library follows Semantic Versioning for its **own** API; its major version is intentionally **not** aligned with Spring Boot's major version. The 5.0.x line is built and verified against **Spring Boot 4.1.0** and also runs on 4.0.x — all Spring Boot starters are `compileOnly`, so your application picks the exact Spring Boot patch version. The `5.0.x` line is a **breaking release** over `4.4.x`; read the **[Migration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/MIGRATION.md)** ("Migrating to 5.0.x") before upgrading — note especially the reverse-proxy `user.security.appUrl` requirement.

### Spring Boot 4.x (Latest)

Spring Boot 4.x brings significant changes including Spring Security 7 and requires Java 21. The 5.x line is built and verified against Spring Boot 4.1.0 and is compatible with 4.0.x.

**Maven:**

<dependency\>
    <groupId\>com.digitalsanctuary</groupId\>
    <artifactId\>ds-spring-user-framework</artifactId\>
    <version\>5.1.1</version\>
</dependency\>

**Gradle:**

implementation 'com.digitalsanctuary:ds-spring-user-framework:5.1.1'

#### Spring Boot 4.x Key Changes

When upgrading to Spring Boot 4.0, be aware of these important changes:

-   **Java 21 Required**: Spring Boot 4.0 requires Java 21 or higher
-   **Spring Security 7**: Includes breaking changes from Spring Security 6.x
    -   All URL patterns in security configuration must start with `/`
    -   Some deprecated APIs have been removed
-   **Jackson 3**: JSON processing uses Jackson 3.x with some API changes
-   **Modular Test Infrastructure**: Test annotations have moved to new packages:
    -   `@AutoConfigureMockMvc` → `org.springframework.boot.webmvc.test.autoconfigure`
    -   `@DataJpaTest` → `org.springframework.boot.data.jpa.test.autoconfigure`
    -   `@WebMvcTest` → `org.springframework.boot.webmvc.test.autoconfigure`

For testing, you may need these additional dependencies:

testImplementation 'org.springframework.boot:spring-boot-data-jpa-test'
testImplementation 'org.springframework.boot:spring-boot-webmvc-test'
testImplementation 'org.springframework.boot:spring-boot-starter-security-test'

**Upgrading from 3.x, or from 4.4.x?** See the [Migration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/MIGRATION.md) for detailed upgrade instructions. The `4.4.x` → `5.0.x` jump is a breaking release (security, schema, API, and auto-configuration changes) — review "Migrating to 5.0.x" before upgrading.

### Spring Boot 3.5 (Stable)

For projects using Spring Boot 3.5.x with Java 17+:

> **Security-maintenance only.** The `3.6.x` line backports security fixes from the 5.0.x line that apply to Spring Boot 3.5; new feature development happens on `5.0.x`. If you are on Java 21 / Spring Boot 4, use `5.0.x`.

**Maven:**

<dependency\>
    <groupId\>com.digitalsanctuary</groupId\>
    <artifactId\>ds-spring-user-framework</artifactId\>
    <version\>3.6.0</version\>
</dependency\>

**Gradle:**

implementation 'com.digitalsanctuary:ds-spring-user-framework:3.6.0'

## Migration Guide

If you're upgrading from a previous version, see the **[Migration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/MIGRATION.md)** for:

-   Step-by-step upgrade instructions
-   Breaking changes and how to address them
-   Spring Security 7 compatibility requirements
-   Test infrastructure changes
-   Guidance for developers extending the framework

## Quick Start

Follow these steps to get up and running with the Spring User Framework in your application.

### Prerequisites

-   **For Spring Boot 4.0**: Java 21 or higher
-   **For Spring Boot 3.5**: Java 17 or higher
-   A database (MariaDB, PostgreSQL, MySQL, H2, etc.)
-   SMTP server for email functionality (optional but recommended)

### Step 1: Add Dependencies

1.  **Add the main framework dependency** (see [Installation](#installation) for version selection):
    
    **Spring Boot 4.0 / 4.1 (Java 21+):**
    
    implementation 'com.digitalsanctuary:ds-spring-user-framework:5.1.1'
    
    **Spring Boot 3.5 (Java 17+):**
    
    implementation 'com.digitalsanctuary:ds-spring-user-framework:3.6.0'
    
2.  **Add required dependencies**:
    
    **Important**: This framework requires these additional Spring Boot starters to function properly:
    
    Maven:
    
    <dependency\>
        <groupId\>org.springframework.boot</groupId\>
        <artifactId\>spring-boot-starter-thymeleaf</artifactId\>
    </dependency\>
    <dependency\>
        <groupId\>org.springframework.boot</groupId\>
        <artifactId\>spring-boot-starter-mail</artifactId\>
    </dependency\>
    <dependency\>
        <groupId\>org.springframework.boot</groupId\>
        <artifactId\>spring-boot-starter-data-jpa</artifactId\>
    </dependency\>
    <dependency\>
        <groupId\>org.springframework.boot</groupId\>
        <artifactId\>spring-boot-starter-security</artifactId\>
    </dependency\>
    <dependency\>
        <groupId\>org.springframework.boot</groupId\>
        <artifactId\>spring-boot-starter-oauth2-client</artifactId\>
    </dependency\>
    <dependency\>
        <groupId\>org.springframework.retry</groupId\>
        <artifactId\>spring-retry</artifactId\>
        <version\>2.0.13</version\>
    </dependency\>
    
    Gradle:
    
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.retry:spring-retry:2.0.13'
    
    **Notes:**
    
    -   `spring-boot-starter-oauth2-client` is required even if you don't plan to use social login. The framework's security chain wires OAuth2 user services at startup; the dependency must be on the classpath so the classes resolve. The OAuth2 login flow itself is disabled by default and opt-in — set `spring.security.oauth2.enabled=true` in your application properties only when you configure OAuth2 provider credentials (this is a framework property, not a standard Spring Security key).
    -   `spring-retry` needs an explicit version because Spring Boot's BOM may not manage this artifact. The version shown matches what the framework is built against.

### Step 2: Database Configuration

Configure your database in `application.yml`. The framework supports all databases compatible with Spring Data JPA:

**MariaDB/MySQL:**

spring:
  datasource:
    url: jdbc:mariadb://localhost:3306/yourdb?createDatabaseIfNotExist=true
    username: dbuser
    password: dbpassword
    driver-class-name: org.mariadb.jdbc.Driver

**PostgreSQL:**

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/yourdb
    username: dbuser
    password: dbpassword
    driver-class-name: org.postgresql.Driver

**H2 (for development/testing):**

spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver

### Step 3: JPA Configuration

spring:
  jpa:
    hibernate:
      ddl-auto: update  # Creates/updates tables automatically
    show-sql: false     # Set to true for SQL debugging

### Step 4: Email Configuration (Optional but Recommended)

If `spring.mail.host` is not configured, the framework starts cleanly but any feature that would send mail (password reset, registration verification) logs a warning and silently skips the send. Configure mail when you want those features to actually deliver messages:

spring:
  mail:
    host: smtp.gmail.com       # or your SMTP server
    port: 587
    username: your-email@gmail.com
    password: your-app-password
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

user:
  mail:
    fromAddress: noreply@yourdomain.com  # Email "from" address

### Step 5: Essential Framework Configuration

Add these minimal settings to get started:

user:
  # Basic security settings
  security:
    defaultAction: deny                    # Secure by default
    bcryptStrength: 12                     # Password hashing strength
    failedLoginAttempts: 5                 # Account lockout threshold
    accountLockoutDuration: 15             # Lockout duration in minutes

  # Registration settings
  registration:
    sendVerificationEmail: false           # true = email verification required
                                          # false = auto-enable accounts

### Step 6: Create User Profile Extension (Optional)

If you need additional user data beyond the built-in fields, create a profile extension:

@Entity
@Table(name = "app\_user\_profile")
public class AppUserProfile extends BaseUserProfile {
    private String department;
    private String phoneNumber;
    private LocalDate birthDate;

    // Getters and setters
    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }

    // ... other getters and setters
}

### Step 7: Start Your Application

1.  **Run your Spring Boot application**:
    
    mvn spring-boot:run
    # or
    ./gradlew bootRun
    
2.  **Verify the framework is working**:
    
    -   Navigate to `http://localhost:8080/user/login.html` to see the login page
    -   Check your database - user tables should be created automatically
    -   Look for framework startup messages in the console

### Step 8: Test Core Features

**Create your first user:**

-   Navigate to `/user/register.html`
-   Fill out the registration form
-   If `sendVerificationEmail=false`, you can login immediately
-   If `sendVerificationEmail=true`, check your email for verification link

**Test login:**

-   Navigate to `/user/login.html`
-   Use the credentials you just created

### Step 9: Customize Pages (Required for user-facing pages)

The framework ships email templates (`templates/mail/*.html`) but does **not** ship the user-facing HTML pages (login, register, forgot-password, etc). You provide those yourself, typically by copying the reference set from the demo app and styling them to match your app.

1.  **Grab the reference templates** from [SpringUserFrameworkDemoApp/src/main/resources/templates/user/](https://github.com/devondragon/SpringUserFrameworkDemoApp/tree/main/src/main/resources/templates/user) and drop them into `src/main/resources/templates/user/` in your project:
    
    -   `login.html` - Login page
    -   `register.html` - Registration page
    -   `forgot-password.html` - Password reset request
    -   `forgot-password-change.html` - Password reset form
    -   `update-password.html` - Authenticated password change
    -   `update-user.html` - Profile update
    -   `registration-complete.html`, `registration-pending-verification.html`, `request-new-verification-email.html`, `forgot-password-pending-verification.html`, `delete-account.html`
    
    The demo's templates use a Thymeleaf layout (`layout.html`) and shared fragments. If you don't want that, strip the `layout:decorate` / `th:fragment` references and inline the markup.
    
2.  **Use your own CSS** by adding stylesheets to `src/main/resources/static/css/`.
    

The framework only requires that the templates exist at the URLs configured under `user.security.*` (e.g. `loginPageURI`, `registrationURI`) and post back to the matching `/user/*` API endpoints; the HTML structure inside them is yours.

### Complete Example Configuration

Here's a complete `application.yml` for a typical setup:

spring:
  datasource:
    url: jdbc:mariadb://localhost:3306/myapp?createDatabaseIfNotExist=true
    username: appuser
    password: apppass
    driver-class-name: org.mariadb.jdbc.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: false

  mail:
    host: smtp.gmail.com
    port: 587
    username: myapp@gmail.com
    password: myapppassword
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

user:
  mail:
    fromAddress: noreply@myapp.com

  security:
    defaultAction: deny
    bcryptStrength: 12
    failedLoginAttempts: 3
    accountLockoutDuration: 30

  registration:
    sendVerificationEmail: true

  # Optional: Audit logging
  audit:
    logEvents: true
    logFilePath: ./logs/audit.log

### Next Steps

-   Read the [Configuration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/CONFIG.md) for advanced settings
-   See [Extension Examples](https://github.com/devondragon/SpringUserFramework/blob/main/PROFILE.md) for custom user profiles
-   Check out the [Demo Application](https://github.com/devondragon/SpringUserFrameworkDemoApp) for a complete example

## Configuration

The framework uses a configuration-first approach to customize behavior. See the [Configuration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/CONFIG.md) for detailed documentation of all configuration options.

Key configuration categories:

-   **Security**: Access control, password policies, CSRF protection
-   **Mail**: Email server settings for verification and notification emails
-   **User Registration**: Self-registration options, verification requirements
-   **Authentication**: Local and OAuth2 provider configuration
-   **UI**: Paths to customized templates and views

## Security Features

### Role-Based Access Control

Define roles and privileges with hierarchical inheritance:

user:
  roles:
    roles-and-privileges:
      "\[ROLE\_ADMIN\]":
        - ADMIN\_PRIVILEGE
        - USER\_MANAGEMENT\_PRIVILEGE
      "\[ROLE\_USER\]":
        - LOGIN\_PRIVILEGE
        - SELF\_SERVICE\_PRIVILEGE
    role-hierarchy:
      - ROLE\_ADMIN > ROLE\_USER

### Account Lockout

Prevent brute force attacks with configurable lockout policies:

user:
  security:
    failedLoginAttempts: 5
    accountLockoutDuration: 30  # minutes

### Audit Logging

Track security-relevant events with built-in audit logging:

user:
  audit:
    logEvents: true
    logFilePath: /path/to/audit/log
    flushOnWrite: false
    flushRate: 10000

### HTMX Support

When HTMX-powered pages make requests (polling, fragment loading, etc.) and the user's session expires, Spring Security's default 302 redirect causes HTMX to swap the full login page HTML into each target element, breaking the UI.

The framework automatically detects HTMX requests (via the `HX-Request` header) and returns a proper 401 response instead:

-   **Status**: `401 Unauthorized`
-   **Header**: `HX-Redirect: <loginUrl>` (triggers HTMX full-page redirect)
-   **Body**: `{"error": "authentication_required", "message": "Session expired. Please log in.", "loginUrl": "<loginUrl>"}`

Non-HTMX browser requests continue to receive the standard 302 redirect to the login page.

**Overriding the default behavior:**

To provide a custom `AuthenticationEntryPoint`, define your own bean and the framework's default will back off automatically:

@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    return new MyCustomAuthenticationEntryPoint();
}

## User Management

### Registration

The registration flow is configurable and can operate in two modes:

**Auto-Enable Mode** (default: `user.registration.sendVerificationEmail=false`):

-   Form submission validation
-   Email uniqueness check
-   User account is immediately enabled and can login
-   No verification email is sent
-   User has full access immediately after registration

**Email Verification Mode** (`user.registration.sendVerificationEmail=true`):

-   Form submission validation
-   Email uniqueness check
-   User account is created but **disabled**
-   Verification email is sent with confirmation link
-   User must click verification link to enable account
-   Account remains disabled until email verification is completed
-   Configurable initial roles assigned after verification

**Configuration Example:**

user:
  registration:
    sendVerificationEmail: true  # Enable email verification (default: false)

**Note:** When email verification is disabled, user accounts are immediately active and functional. When enabled, accounts require email confirmation before login is possible.

### Profile Management

Users can:

-   Update their profile information
-   Change their password
-   Delete their account (configurable to either disable or fully delete)

### Admin Password Reset

Administrators can trigger password resets for users programmatically:

@Autowired
private UserEmailService userEmailService;

// Reset password and invalidate all user sessions
int sessionsInvalidated = userEmailService.initiateAdminPasswordReset(user, appUrl, true);

// Reset password without invalidating sessions
userEmailService.initiateAdminPasswordReset(user, appUrl, false);

// Use configured appUrl (from user.admin.appUrl property)
userEmailService.initiateAdminPasswordReset(user);

**Features:**

-   Requires `ROLE_ADMIN` authorization (`@PreAuthorize`)
-   Optional session invalidation to force re-authentication
-   Sends password reset email with secure token
-   Comprehensive audit logging with correlation IDs
-   Cryptographically secure tokens (256-bit entropy)

**Configuration:**

user:
  admin:
    appUrl: https://myapp.com  # Base URL for password reset links

**Security Notes:**

-   Admin identity is derived from `SecurityContext`, not user input
-   Sessions are invalidated _after_ email is sent to prevent lockout
-   URL validation prevents XSS (blocks javascript:, data: schemes)

## Email Verification

The framework includes a complete email verification system:

-   Token generation and verification
-   Customizable email templates
-   Token expiration and renewal
-   Automatic account activation

## Authentication

### Local Authentication

Username/password authentication with:

-   Secure password hashing (bcrypt)
-   Account lockout protection
-   Remember-me functionality

### WebAuthn / Passkeys

Passwordless authentication using biometrics (Touch ID, Face ID, Windows Hello), security keys (YubiKey), or device-based credentials. Built on Spring Security's WebAuthn support.

**Features:**

-   Passwordless login via platform authenticators and roaming security keys
-   Passkey management REST API (list, rename, delete credentials)
-   Last-credential protection (prevents lockout if user has no password)
-   Synced passkey support (iCloud Keychain, Google Password Manager, etc.)
-   Automatic cleanup of passkey data when a user account is deleted
-   Disabled by default; must be explicitly enabled with required database tables

**Setup:**

1.  Enable WebAuthn in your configuration:
    
    user:
      webauthn:
        enabled: true
        rpId: localhost                           # Your domain in production
        rpName: My Application
        allowedOrigins: https://localhost:8443    # Must match browser origin
    
2.  Add the WebAuthn authentication endpoints to your unprotected URIs:
    
    user:
      security:
        unprotectedURIs: ...,/webauthn/authenticate/\*\*,/login/webauthn
    
3.  Create the required database tables. If using `ddl-auto: update`, Hibernate will create them automatically. Otherwise, apply the schema manually (see `db-scripts/mariadb-schema.sql`).
    

**Requirements:**

-   HTTPS is required in production (HTTP works on `localhost` for development)
-   Users must be authenticated before registering a passkey
-   See the [Configuration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/CONFIG.md) for all WebAuthn settings

**Management API Endpoints** (all require authentication):

Endpoint

Method

Description

`/user/webauthn/credentials`

GET

List user's passkeys

`/user/webauthn/has-credentials`

GET

Check if user has passkeys

`/user/webauthn/credentials/{id}/label`

PUT

Rename a passkey (max 64 chars)

`/user/webauthn/credentials/{id}`

DELETE

Delete a passkey

### OAuth2/SSO

Support for social login providers:

-   Google
-   Facebook
-   Apple
-   Keycloak
-   Custom providers

Configuration example:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR\_GOOGLE\_CLIENT\_ID
            client-secret: YOUR\_GOOGLE\_CLIENT\_SECRET
            redirect-uri: "{baseUrl}/login/oauth2/code/google"
          facebook:
            client-id: YOUR\_FACEBOOK\_CLIENT\_ID
            client-secret: YOUR\_FACEBOOK\_CLIENT\_SECRET
            redirect-uri: "{baseUrl}/login/oauth2/code/facebook"
          keycloak:
            client-id: YOUR\_KEYCLOAK\_CLIENT\_ID
            client-secret: YOUR\_KEYCLOAK\_CLIENT\_SECRET
            redirect-uri: "{baseUrl}/login/oauth2/code/keycloak"

For public OAuth you will need a public hostname and HTTPS enabled. You can use ngrok or Cloudflare tunnels to create a public hostname and tunnel to your local machine during development. You can then use the ngrok hostname in your Google, Facebook and Keycloak developer console configuration.

#### **SSO OIDC with Keycloak**

To enable SSO:

1.  Create OIDC client in Keycloak admin console.
2.  Update your `application-docker-keycloak.yml`:
    
    spring:
      security:
        oauth2:
          client:
             registration:
               keycloak:
                 client-id: ${DS\_SPRING\_USER\_KEYCLOAK\_CLIENT\_ID} # Keycloak client ID for OAuth2
                 client-secret: ${DS\_SPRING\_USER\_KEYCLOAK\_CLIENT\_SECRET} # Keycloak client secret for OAuth2
                 authorization-grant-type: authorization\_code # Authorization grant type for OAuth2
                 scope:
                   - email # Request email scope for OAuth2
                   - profile # Request profile scope for OAuth2
                   - openid # Request oidc scope for OAuth2
                 client-name: Keycloak # Name of the OAuth2 client
                 provider: keycloak
             provider:
               keycloak: # https://www.keycloak.org/securing-apps/oidc-layers
                 issuer-uri: ${DS\_SPRING\_USER\_KEYCLOAK\_PROVIDER\_ISSUER\_URI}
                 authorization-uri: ${DS\_SPRING\_USER\_KEYCLOAK\_PROVIDER\_AUTHORIZATION\_URI}
                 token-uri: ${DS\_SPRING\_USER\_KEYCLOAK\_PROVIDER\_TOKEN\_URI}
                 user-info-uri: ${DS\_SPRING\_USER\_KEYCLOAK\_PROVIDER\_USER\_INFO\_URI}
                 user-name-attribute: preferred\_username # https://www.keycloak.org/docs-api/latest/rest-api/index.html#UserRepresentation
                 jwk-set-uri: ${DS\_SPRING\_USER\_KEYCLOAK\_PROVIDER\_JWK\_SET\_URI}
    

### Dev Login (Local Development)

The framework includes a built-in dev login controller that lets developers quickly switch between user accounts without entering passwords. This eliminates the need for consuming applications to write boilerplate dev-login controllers.

**Setup:**

1.  Activate the `local` Spring profile (e.g., `spring.profiles.active=local`)
2.  Enable dev login in your configuration:

# application-local.yml
user:
  dev:
    auto-login-enabled: true
    login-redirect-url: /dashboard  # optional, defaults to /

**Endpoints** (only available when enabled with the `local` profile):

Endpoint

Method

Description

`/dev/login-as/{email}`

GET

Authenticate as the specified user and redirect

`/dev/users`

GET

List all enabled user emails (JSON)

**Example usage during development:**

-   Visit `http://localhost:8080/dev/users` to see available accounts
-   Visit `http://localhost:8080/dev/login-as/admin@example.com` to instantly log in as that user

**Security:** This feature requires **both** `user.dev.auto-login-enabled=true` **and** the `local` Spring profile to be active. A prominent warning banner is logged on startup when dev login is active. **Never enable this in production.**

See the [Configuration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/CONFIG.md) for all dev login settings.

## Extensibility

The framework is designed to be extended without modifying the core code.

### Custom User Profiles

Extend the `BaseUserProfile` to add your application-specific user data:

@Service
public class CustomUserProfileService implements UserProfileService<CustomUserProfile\> {
    @Override
    public CustomUserProfile getOrCreateProfile(User user) {
        // Implementation
    }

    @Override
    public CustomUserProfile updateProfile(CustomUserProfile profile) {
        // Implementation
    }
}

Read more in the [Profile Guide](https://github.com/devondragon/SpringUserFramework/blob/main/PROFILE.md).

### Handling User Account Deletion and Profile Cleanup

By default, when a user account is "deleted" through the framework's services or APIs, the account is marked as disabled (`enabled=false`) rather than being physically removed from the database. This is controlled by the `user.actuallyDeleteAccount` configuration property, which defaults to `false`.

#### Enabling Actual Deletion

If you require user accounts to be physically deleted from the database, set the following property in your `application.properties` or `application.yml`:

user.actuallyDeleteAccount\=true

Cleaning Up Related Data (e.g., User Profiles) When user.actuallyDeleteAccount is set to true, the framework needs a way to ensure that related data, such as application-specific user profiles extending BaseUserProfile, is also cleaned up to avoid orphaned data or foreign key constraint violations.

To facilitate this in a decoupled manner, the framework publishes a UserPreDeleteEvent immediately before the User entity is deleted from the database. This event is published within the same transaction as the user deletion.

Consuming applications that have extended BaseUserProfile (or have other user-related data) should listen for this event and perform the necessary cleanup operations.

Event Class: com.digitalsanctuary.spring.user.event.UserPreDeleteEvent Event Data: Contains the User entity that is about to be deleted (event.getUser()).

Example Event Listener:

Here's an example of how a consuming application can implement an event listener to delete its specific user profile (DemoUserProfile in this case) when a user is deleted:

package com.digitalsanctuary.spring.demo.user.profile;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.digitalsanctuary.spring.user.event.UserPreDeleteEvent;

/\*\*
 \* Listener for user profile deletion events. This class listens for UserPreDeleteEvent and deletes the associated DemoUserProfile. It is assumed that
 \* the DemoUserProfile is mapped to the User entity with a one-to-one relationship.
 \*/
@Component
@RequiredArgsConstructor
@Slf4j
public class UserProfileDeletionListener {
    private final DemoUserProfileRepository demoUserProfileRepository;
    // Inject other repositories if needed (e.g., EventRegistrationRepository)

    @EventListener
    @Transactional // Joins the transaction started by UserService.deleteUserAccount
    public void handleUserPreDelete(UserPreDeleteEvent event) {
        Long userId = event.getUser().getId();
        log.info("Received UserPreDeleteEvent for userId: {}. Deleting associated DemoUserProfile...", userId);

        // Option 1: Delete profile directly (if no further cascades needed from profile)
        // Since DemoUserProfile uses @MapsId, its ID is the same as the User's ID
        demoUserProfileRepository.findById(userId).ifPresent(profile -> {
            log.debug("Found DemoUserProfile for userId: {}. Deleting...", userId);
            // If DemoUserProfile itself has relationships needing cleanup (like EventRegistrations)
            // that aren't handled by CascadeType.REMOVE or orphanRemoval=true,
            // handle them here \*before\* deleting the profile.
            // Example: eventRegistrationRepository.deleteByUserProfile(profile);
            demoUserProfileRepository.delete(profile);
            log.debug("DemoUserProfile deleted for userId: {}", userId);
        });

        // Option 2: If DemoUserProfile has CascadeType.REMOVE/orphanRemoval=true
        // on its collections (like eventRegistrations), deleting the profile might be enough.
        // demoUserProfileRepository.deleteById(userId);

        log.info("Finished processing UserPreDeleteEvent for userId: {}", userId);
    }
}

By implementing such a listener, your application ensures data integrity when the actual user account deletion feature is enabled, without requiring the core framework library to have knowledge of your specific profile entities. If you leave user.actuallyDeleteAccount as false, this event is not published, and no listener implementation is required for profile cleanup

### SSO OAuth2 with Google and Facebook

The framework supports SSO OAuth2 with Google, Facebook and Keycloak. To enable this you need to configure the client id and secret for each provider. This is done in the application.yml (or application.properties) file using the [Spring Security OAuth2 properties](https://docs.spring.io/spring-security/reference/servlet/oauth2/login/core.html). You can see the example configuration in the Demo Project's `application.yml` file.

## GDPR Compliance

The framework provides opt-in GDPR compliance features to help your application meet European data protection requirements. These features are **disabled by default** and must be explicitly enabled.

### Enabling GDPR Features

Add the following to your `application.yml`:

user:
  gdpr:
    enabled: true                    # Master toggle for all GDPR features
    exportBeforeDeletion: true       # Automatically export data before deletion
    consentTracking: true            # Enable consent grant/withdrawal tracking

When enabled, the following REST endpoints become available (all require authentication):

Endpoint

Method

Description

`/user/gdpr/export`

GET

Export all user data as JSON

`/user/gdpr/delete`

POST

Request account deletion

`/user/gdpr/consent`

POST

Record consent grant or withdrawal

`/user/gdpr/consent/status`

GET

Get current consent status

### Data Export (Right of Access)

Users can request a complete export of their data via the `/user/gdpr/export` endpoint. The export includes:

-   **User account data**: Name, email, registration date, roles
-   **Audit history**: Login events, password changes, profile updates
-   **Consent records**: All consent grants and withdrawals with timestamps
-   **Token metadata**: Verification and password reset token expiry (not actual tokens)
-   **Custom data**: Any data contributed by registered `GdprDataContributor` beans

**Example Response:**

{
  "success": true,
  "data": {
    "exportedAt": "2024-01-15T10:30:00Z",
    "user": {
      "id": 123,
      "email": "user@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "createdDate": "2023-06-01T08:00:00Z",
      "roles": \["ROLE\_USER"\]
    },
    "auditHistory": \[...\],
    "consents": \[...\],
    "customData": {}
  }
}

### Account Deletion (Right to be Forgotten)

Users can request complete deletion of their account via the `/user/gdpr/delete` endpoint. The deletion process:

1.  **Exports data** (if `exportBeforeDeletion=true`) and includes it in the response
2.  **Notifies contributors** via `GdprDataContributor.prepareForDeletion()`
3.  **Publishes `UserPreDeleteEvent`** for custom cleanup listeners
4.  **Deletes framework data**: Verification tokens, password reset tokens, password history
5.  **Deletes user entity** from database
6.  **Publishes `UserDeletedEvent`** for post-deletion processing
7.  **Invalidates all sessions** across all devices
8.  **Logs out** the current session

**Important**: This performs a hard delete. Ensure you have the `UserPreDeleteEvent` listener configured (see [Handling User Account Deletion](#handling-user-account-deletion-and-profile-cleanup)) to clean up related data.

### Consent Management

Track user consent for various purposes (marketing, analytics, data processing, etc.):

**Recording Consent:**

# Grant consent
curl -X POST /user/gdpr/consent \\
  -H "Content-Type: application/json" \\
  -d '{"consentType": "MARKETING", "granted": true}'

# Withdraw consent
curl -X POST /user/gdpr/consent \\
  -H "Content-Type: application/json" \\
  -d '{"consentType": "MARKETING", "granted": false}'

# Custom consent type
curl -X POST /user/gdpr/consent \\
  -H "Content-Type: application/json" \\
  -d '{"consentType": "CUSTOM", "customType": "newsletter\_weekly", "granted": true}'

**Built-in Consent Types:**

-   `MARKETING` - Marketing communications
-   `ANALYTICS` - Analytics and tracking
-   `THIRD_PARTY` - Third-party data sharing
-   `PROFILING` - User profiling
-   `CUSTOM` - Application-specific (requires `customType` field)

**Checking Consent Status:**

curl /user/gdpr/consent/status?type=MARKETING

All consent changes are recorded in the audit log with timestamps, IP addresses, and user agent information.

### Extending GDPR Exports

To include your application's custom data in GDPR exports, implement the `GdprDataContributor` interface:

@Component
public class OrderDataContributor implements GdprDataContributor {

    private final OrderRepository orderRepository;

    public OrderDataContributor(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Override
    public String getDataKey() {
        return "orders";  // Key in the export JSON
    }

    @Override
    public Object contributeData(User user) {
        // Return data to include in export (will be serialized to JSON)
        return orderRepository.findByUserId(user.getId())
            .stream()
            .map(this::toExportDto)
            .toList();
    }

    @Override
    public void prepareForDeletion(User user) {
        // Clean up data before user deletion (runs within transaction)
        // WARNING: Only delete LOCAL database data here, not external APIs
        orderRepository.deleteByUserId(user.getId());
    }

    private OrderExportDto toExportDto(Order order) {
        // Map to DTO for export
    }
}

**Important**: The `prepareForDeletion()` method runs within the same database transaction as user deletion. Only perform local database operations here. For external API cleanup, use a `UserDeletedEvent` listener instead.

### GDPR Events

The framework publishes Spring events for GDPR operations:

Event

When Published

Use Case

`UserPreDeleteEvent`

Before user deletion (in transaction)

Clean up related database records

`UserDeletedEvent`

After successful deletion

External API cleanup, notifications

`UserDataExportedEvent`

After data export

Audit logging, analytics

`ConsentChangedEvent`

After consent grant/withdrawal

Trigger consent-dependent workflows

**Example: External Cleanup After Deletion**

@Component
public class ExternalCleanupListener {

    @EventListener
    @Async  // Run asynchronously after transaction commits
    public void onUserDeleted(UserDeletedEvent event) {
        // Safe to call external APIs here
        externalCrmService.deleteCustomer(event.getUserEmail());
        analyticsService.anonymizeUser(event.getUserId());
    }
}

## Examples

For complete working examples, check out the [Spring User Framework Demo Application](https://github.com/devondragon/SpringUserFrameworkDemoApp).

## Contributing

We welcome contributions of all kinds! If you'd like to help improve SpringUserFramework, please read our [Contributing Guide](https://github.com/devondragon/SpringUserFramework/blob/main/CONTRIBUTING.md) for details on how to get started, report issues, and submit pull requests. Let's build something great together!

## Reference Documentation

-   [API Documentation](https://digitalsanctuary.github.io/SpringUserFramework/)
-   [Migration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/MIGRATION.md)
-   [Configuration Guide](https://github.com/devondragon/SpringUserFramework/blob/main/CONFIG.md)
-   [Security Guide](https://github.com/devondragon/SpringUserFramework/blob/main/SECURITY.md)
-   [Customization Guide](https://github.com/devondragon/SpringUserFramework/blob/main/CUSTOMIZATION.md)
-   [Demo Application](https://github.com/devondragon/SpringUserFrameworkDemoApp)

## License

This project is licensed under the Apache License 2.0 - see the [LICENSE](https://github.com/devondragon/SpringUserFramework/blob/main/LICENSE) file for details.

* * *

Created by [Devon Hillard](https://github.com/devondragon/) at [Digital Sanctuary](https://www.digitalsanctuary.com/)