### Test Security Constraints with MockMvc (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Shows how to test security configurations using MockMvc. Includes examples for verifying unauthorized access and allowing access for authenticated users. ```java @Test void shouldRequireAuthentication() throws Exception { mockMvc.perform(get("/user/profile")) .andExpect(status().isUnauthorized()); } @Test void shouldAllowAccessForValidUser() throws Exception { mockMvc.perform(get("/user/profile") .with(user(TestFixtures.Security.standardUserDetails()))) .andExpect(status().isOk()); } ``` -------------------------------- ### Complete Application Configuration (YAML) Source: https://github.com/devondragon/springuserframework/blob/main/README.md A comprehensive example of the application.yml file for a typical Spring User Framework setup. It includes database, JPA, mail, security, registration, and audit logging configurations. ```yaml 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 ``` -------------------------------- ### Start Demo App Database with Docker Compose Source: https://github.com/devondragon/springuserframework/blob/main/CONTRIBUTING.md Instructions to start the database for the SpringUserFrameworkDemoApp using Docker Compose, useful for testing database-related features. ```bash cd SpringUserFrameworkDemoApp docker-compose up -d ``` -------------------------------- ### Build Project with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/PUBLISH.md Builds the project using the Gradle wrapper. This command compiles the code, runs tests, and packages the artifacts. It is a prerequisite for publishing. ```shell ./gradlew build ``` -------------------------------- ### Run Specific Test Categories with Gradle (Bash) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Examples of running specific categories of tests using Gradle's `--tests` argument. This is useful for isolating unit, integration, or specific test classes. ```bash # Run only unit tests (ServiceTest) ./gradlew test --tests "*ServiceTest" # Run only integration tests ./gradlew test --tests "*IntegrationTest" # Run specific test class ./gradlew test --tests "UserServiceTest" ``` -------------------------------- ### Use Fluent Assertions with AssertJ (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Shows examples of using AssertJ's fluent assertion style for more readable and expressive test verifications. Contrasts with traditional JUnit assertions. ```java // Good assertThat(user.getEmail()).isEqualTo("test@example.com"); assertThat(users).hasSize(3) .extracting(User::getEmail) .containsExactly("user1@test.com", "user2@test.com", "user3@test.com"); // Avoid assertEquals("test@example.com", user.getEmail()); ``` -------------------------------- ### OAuth2/SSO Client Configuration (YAML) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Provides example YAML configurations for setting up OAuth2/SSO clients for social login providers like Google, Facebook, and Keycloak. This configuration is essential for enabling external authentication providers. ```yaml 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" ``` -------------------------------- ### Implement Arrange-Act-Assert Test Structure (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Illustrates the Arrange-Act-Assert pattern for structuring unit tests. This pattern promotes clear separation of test setup, execution, and verification steps. ```java @Test void shouldUpdateUserProfile() { // Arrange (Given) User user = TestFixtures.Users.standardUser(); UserDto updateDto = TestFixtures.DTOs.profileUpdate(); when(userRepository.save(any())).thenReturn(user); // Act (When) User updatedUser = userService.updateProfile(user, updateDto); // Assert (Then) assertThat(updatedUser.getFirstName()).isEqualTo("Updated"); verify(userRepository).save(user); } ``` -------------------------------- ### Run Spring Boot Application (Maven & Gradle) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Commands to start your Spring Boot application using either Maven or Gradle. After running, you can access the application via `http://localhost:8080`. ```bash mvn spring-boot:run ``` ```bash ./gradlew bootRun ``` -------------------------------- ### Test OAuth2 Authentication with MockMvc (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Provides an example of testing endpoints secured by OAuth2 using Spring's MockMvc and the `oauth2Login()` mock. This allows simulating authenticated OAuth2 user requests. ```java @Test void shouldAuthenticateWithOAuth2() throws Exception { mockMvc.perform(post("/api/secure-endpoint") .with(oauth2Login().oauth2User(TestFixtures.OAuth2.googleUser()))) .andExpect(status().isOk()); } ``` -------------------------------- ### Create Custom Test Data with Builders (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Demonstrates using fluent builders to construct custom user and role objects for testing. This approach enhances readability and maintainability of test data setup. ```java User customUser = UserTestDataBuilder.aUser() .withEmail("custom@test.com") .withFirstName("Custom") .withLastName("User") .withRole("ROLE_ADMIN") .verified() .build(); Role customRole = RoleTestDataBuilder.aRole() .withName("ROLE_CUSTOM") .withPrivilege("CUSTOM_PRIVILEGE") .build(); ``` -------------------------------- ### Extending Security Configuration Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Guidelines for developers extending the framework's security configuration, focusing on URL patterns, lambda DSL, and method security annotations. ```APIDOC ## Extending Security Configuration ### Description If you have a custom `WebSecurityConfig` or extend the framework's security configuration, review these points for compatibility with Spring Security 7 and Spring Boot 4.0. ### Method N/A (Configuration changes) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Key Changes & Recommendations 1. **URL Patterns**: Ensure all URL patterns in your security configuration start with `/`. 2. **Lambda DSL Style**: Update your configuration to use the lambda DSL style, which is required in Spring Security 7. 3. **Method Security Annotations**: Annotations like `@PreAuthorize` and `@PostAuthorize` remain unchanged. ### Example Custom Security Configuration ```java @Configuration @EnableWebSecurity public class CustomSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authz -> authz // All patterns must start with / .requestMatchers("/api/public/**").permitAll() .requestMatchers("/api/admin/**").hasRole("ADMIN") .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/user/login.html") .permitAll() ); return http.build(); } } ``` ``` -------------------------------- ### Custom Controllers Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Guidance for developers working with custom controllers, specifically regarding DTO usage for profile updates and validation. ```APIDOC ## Custom Controllers ### Description Guidance for developers whose custom controllers extend or work alongside framework controllers. Focuses on DTO updates and validation. ### Method N/A (Code changes) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Key Points 1. **DTOs**: Update any code that uses `UserDto` for profile updates to now use `UserProfileUpdateDto`. 2. **Validation**: Bean validation mechanisms remain the same. 3. **Response Format**: The `JSONResponse` structure is unchanged. ``` -------------------------------- ### Update Security Configuration to Lambda DSL Style Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Provides an example of updating a custom security configuration to use the lambda DSL style, which is required in Spring Security 7 and used in Spring Boot 4.x. This ensures compatibility with the latest security features and syntax. ```java @Configuration @EnableWebSecurity public class CustomSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authz -> authz // All patterns must start with / .requestMatchers("/api/public/**").permitAll() .requestMatchers("/api/admin/**").hasRole("ADMIN") .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/user/login.html") .permitAll() ); return http.build(); } } ``` -------------------------------- ### Complete Application Configuration (YAML) Source: https://context7.com/devondragon/springuserframework/llms.txt Provides a comprehensive example of the application.yml file for configuring the Spring User Framework. It includes settings for data source, JPA, mail, security (OAuth2, password policies, URIs), registration, session management, roles, and logging. ```yaml # application.yml - Complete Configuration Example spring: datasource: url: jdbc:mariadb://localhost:3306/myapp?createDatabaseIfNotExist=true username: dbuser password: dbpassword 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: app-specific-password properties: mail: smtp: auth: true starttls: enable: true security: oauth2: enabled: true client: registration: google: client-id: ${GOOGLE_CLIENT_ID} client-secret: ${GOOGLE_CLIENT_SECRET} redirect-uri: "{baseUrl}/login/oauth2/code/google" scope: - email - profile facebook: client-id: ${FACEBOOK_CLIENT_ID} client-secret: ${FACEBOOK_CLIENT_SECRET} redirect-uri: "{baseUrl}/login/oauth2/code/facebook" scope: - email - public_profile keycloak: client-id: ${KEYCLOAK_CLIENT_ID} client-secret: ${KEYCLOAK_CLIENT_SECRET} authorization-grant-type: authorization_code scope: - email - profile - openid provider: keycloak provider: keycloak: issuer-uri: ${KEYCLOAK_ISSUER_URI} authorization-uri: ${KEYCLOAK_AUTH_URI} token-uri: ${KEYCLOAK_TOKEN_URI} user-info-uri: ${KEYCLOAK_USERINFO_URI} jwk-set-uri: ${KEYCLOAK_JWK_URI} user-name-attribute: preferred_username user: # Mail settings mail: fromAddress: noreply@myapp.com # Admin settings admin: appUrl: https://myapp.com # Security settings security: defaultAction: deny bcryptStrength: 12 failedLoginAttempts: 5 accountLockoutDuration: 30 # URI configuration loginPageURI: /user/login.html loginActionURI: /user/login loginSuccessURI: /dashboard logoutActionURI: /user/logout logoutSuccessURI: /user/login.html?logout registrationURI: /user/register.html registrationPendingURI: /user/registration-pending.html registrationSuccessURI: /user/registration-success.html forgotPasswordURI: /user/forgot-password.html forgotPasswordPendingURI: /user/forgot-password-pending.html forgotPasswordChangeURI: /user/change-password.html registrationNewVerificationURI: /user/resend-verification.html # Protected and unprotected URIs (comma-separated) protectedURIs: /admin/**,/api/private/** unprotectedURIs: /,/css/**,/js/**,/images/**,/favicon.ico,/error,/api/public/** disableCSRFURIs: /api/webhooks/** # Remember-me configuration rememberMe: enabled: true key: ${REMEMBER_ME_SECRET_KEY} # Password policy password: enabled: true min-length: 8 max-length: 128 require-uppercase: true require-lowercase: true require-digit: true require-special: true special-chars: "~`!@#$%^&*()_-+={}[]|\:;\"'<>,.?/" prevent-common-passwords: true history-count: 3 similarity-threshold: 80 # Registration settings registration: sendVerificationEmail: true # Account deletion behavior actuallyDeleteAccount: false # Audit logging audit: logEvents: true logFilePath: ./logs/audit.log flushOnWrite: false flushRate: 10000 # Session settings session: invalidation: warn-threshold: 1000 # Role and privilege configuration roles: roles-and-privileges: "[ROLE_ADMIN]": - ADMIN_PRIVILEGE - USER_MANAGEMENT_PRIVILEGE - AUDIT_VIEW_PRIVILEGE "[ROLE_USER]": - LOGIN_PRIVILEGE - PROFILE_UPDATE_PRIVILEGE - SELF_SERVICE_PRIVILEGE "[ROLE_MODERATOR]": - CONTENT_MODERATION_PRIVILEGE - USER_VIEW_PRIVILEGE role-hierarchy: - ROLE_ADMIN > ROLE_MODERATOR - ROLE_MODERATOR > ROLE_USER server: servlet: session: timeout: 30m logging: level: com.digitalsanctuary.spring.user: DEBUG file: name: ./logs/application.log ``` -------------------------------- ### Create Release and Publish to Maven Central with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/PUBLISH.md Creates a new release version of the project and publishes it to Maven Central. This command typically handles version bumping, tagging, and the final publication process. It is a comprehensive command for releasing software. ```shell gradle release ``` -------------------------------- ### Verify Mock Interactions with ArgumentCaptors (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Demonstrates using ArgumentCaptors to capture arguments passed to mocked methods, enabling complex verification scenarios, such as checking event payloads. ```java @Test void shouldPublishAuditEvent() { // Act userService.registerUser(userDto); // Assert ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(AuditEvent.class); verify(eventPublisher).publishEvent(eventCaptor.capture()); AuditEvent event = eventCaptor.getValue(); assertThat(event.getAction()).isEqualTo("Registration"); assertThat(event.getActionStatus()).isEqualTo("Success"); } ``` -------------------------------- ### Publish to Local Maven Repository with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/PUBLISH.md Publishes the project's artifacts to the local Maven repository. This is useful for testing publications before deploying to remote repositories. It requires the project to be built first. ```shell gradle publishLocal ``` -------------------------------- ### Run Tests with Specific JDK Versions (Bash) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Commands to execute tests using specific JDK versions (17 and 21) via Gradle. This allows for testing compatibility across different Java environments. ```bash ./gradlew testJdk17 # Run with JDK 17 ./gradlew testJdk21 # Run with JDK 21 ./gradlew testAll # Run with both JDK versions ``` -------------------------------- ### Selective Test Execution with Tags (Bash) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Bash commands using Gradle to run tests based on JUnit 5 tags. It shows how to include specific tags ('fast') or exclude others ('slow'). ```bash # Run only fast tests ./gradlew test --tests "*" -Dgroups="fast" # Exclude slow tests ./gradlew test --tests "*" -DexcludedGroups="slow" ``` -------------------------------- ### Test Exception Handling (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Demonstrates how to test that specific exceptions are thrown under certain conditions using AssertJ's `assertThatThrownBy`. This verifies correct error handling in the application. ```java @Test void shouldThrowExceptionForDuplicateEmail() { // Given when(userRepository.findByEmail("test@example.com")).thenReturn(existingUser); // When & Then assertThatThrownBy(() -> userService.registerUser(userDto)) .isInstanceOf(UserAlreadyExistException.class) .hasMessageContaining("email address"); } ``` -------------------------------- ### Debug Gradle Tests Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md This snippet shows how to run Gradle tests with different levels of logging and debugging. It includes commands for enabling debug logging for Spring Security, running a single test with detailed information, and enabling JVM debugging for test execution. ```bash # Run with debug logging ./gradlew test -Dlogging.level.org.springframework.security=DEBUG # Run single test with full output ./gradlew test --tests "UserServiceTest.shouldRegisterUser" --info # Debug test execution ./gradlew test --debug-jvm ``` -------------------------------- ### Publish to Maven Central with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/PUBLISH.md Publishes the project's artifacts to the public Maven Central repository. This makes the project widely available to other developers. Requires proper signing and configuration for Maven Central. ```shell gradle publishMavenCentral ``` -------------------------------- ### Jackson 3 Changes Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Details on changes related to Jackson 3.x usage in Spring Boot 4.0, including ObjectMapper instantiation and potential package shifts. ```APIDOC ## Jackson 3 Changes ### Description Spring Boot 4.0 uses Jackson 3.x for JSON processing. This section outlines the changes in ObjectMapper instantiation and potential package migrations. ### Method N/A (Code changes) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Examples #### ObjectMapper Instantiation ```java // Before (Jackson 2.x) ObjectMapper mapper = new ObjectMapper(); // After (Jackson 3.x) ObjectMapper mapper = JsonMapper.builder().build(); ``` #### Package Changes - Some classes moved from `com.fasterxml.jackson` to new packages. - Review any custom serializers/deserializers for compatibility. ``` -------------------------------- ### Test Email Sending Logic (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Illustrates testing email sending functionality by capturing arguments passed to the mail service. This verifies that the correct email content and recipients are used. ```java @Test void shouldSendVerificationEmail() { // Act userEmailService.sendRegistrationVerificationEmail(user, appUrl); // Assert ArgumentCaptor> variablesCaptor = ArgumentCaptor.forClass(Map.class); verify(mailService).sendTemplateMessage( eq(user.getEmail()), eq("Registration Confirmation"), variablesCaptor.capture(), eq("mail/registration-token.html") ); Map variables = variablesCaptor.getValue(); assertThat(variables).containsKeys("token", "user", "confirmationUrl"); } ``` -------------------------------- ### Publish to Private Maven Repository (Reposilite) with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/PUBLISH.md Publishes the project's artifacts to a private Maven repository, specifically configured for Reposilite. This allows for internal sharing of artifacts. Ensure the repository is accessible and configured correctly. ```shell gradle publishReposilite ``` -------------------------------- ### Add Test Dependencies for Spring Boot 4.0 (Gradle) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Includes necessary test dependencies for Spring Boot 4.0 applications using Gradle, covering core, data JPA, web MVC, and security testing. ```groovy testImplementation 'org.springframework.boot:spring-boot-starter-test' 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' testImplementation 'org.springframework.security:spring-security-test' ``` -------------------------------- ### Configure Essential Framework Settings (application.yml) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Sets up fundamental framework configurations including basic security defaults like `defaultAction`, `bcryptStrength`, and lockout policies, as well as registration settings such as `sendVerificationEmail`. ```yaml user: security: defaultAction: deny bcryptStrength: 12 failedLoginAttempts: 5 accountLockoutDuration: 15 registration: sendVerificationEmail: false ``` -------------------------------- ### Bash: Gradle Build and Test Commands Source: https://context7.com/devondragon/springuserframework/llms.txt Provides common Gradle commands for building, testing, and managing the Spring User Framework project during development. Includes commands for building, running tests (all, specific, different JDKs), code quality checks, local publishing, cleaning artifacts, and running with debug logging. ```bash # Build the project ./gradlew build # Run all tests ./gradlew test # Run a specific test class ./gradlew test --tests "com.digitalsanctuary.spring.user.service.UserServiceTest" # Run tests with specific JDK version ./gradlew testJdk17 ./gradlew testJdk21 # Run tests on all supported JDK versions ./gradlew testAll # Check code quality (linting) ./gradlew check # Publish to local Maven repository (for testing in consuming apps) ./gradlew publishLocal # Clean build artifacts ./gradlew clean # Build without running tests ./gradlew build -x test # Run with debug logging ./gradlew test --debug ``` -------------------------------- ### Utilize TestFixtures for Test Data (Java) Source: https://github.com/devondragon/springuserframework/blob/main/TESTING.md Java code snippet showcasing the `TestFixtures` utility class for generating consistent test data. It provides examples for standard users, DTOs, OAuth2 users, security details, and registration scenarios. ```java // Standard test entities User user = TestFixtures.Users.standardUser(); User admin = TestFixtures.Users.adminUser(); User locked = TestFixtures.Users.lockedUser(); // DTOs for API testing UserDto registration = TestFixtures.DTOs.validUserRegistration(); PasswordDto passwordUpdate = TestFixtures.DTOs.validPasswordUpdate(); // OAuth2 test users OAuth2User googleUser = TestFixtures.OAuth2.googleUser(); OAuth2User githubUser = TestFixtures.OAuth2.githubUser(); // Security contexts DSUserDetails userDetails = TestFixtures.Security.standardUserDetails(); // Test scenarios TestFixtures.Scenarios.UserRegistration scenario = new TestFixtures.Scenarios.UserRegistration(); ``` -------------------------------- ### Configure Database Connection (application.yml) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Sets up the datasource properties in application.yml for various databases including MariaDB/MySQL, PostgreSQL, and H2. Ensure the `url`, `username`, `password`, and `driver-class-name` are correctly configured for your environment. ```yaml spring: datasource: url: jdbc:mariadb://localhost:3306/yourdb?createDatabaseIfNotExist=true username: dbuser password: dbpassword driver-class-name: org.mariadb.jdbc.Driver ``` ```yaml spring: datasource: url: jdbc:postgresql://localhost:5432/yourdb username: dbuser password: dbpassword driver-class-name: org.postgresql.Driver ``` ```yaml spring: datasource: url: jdbc:h2:mem:testdb driver-class-name: org.h2.Driver ``` -------------------------------- ### Profile-Based Authorization in Spring (Java) Source: https://github.com/devondragon/springuserframework/blob/main/PROFILE.md An example of using Spring Security's `@PreAuthorize` annotation to restrict access to a controller method based on the user's profile. This specific example requires the user to be a premium user to access the `/premium-content` endpoint. ```java @PreAuthorize("@appSessionProfile.isPremiumUser()") @GetMapping("/premium-content") public String premiumContent() { return "premium/content"; } ``` -------------------------------- ### Clone and Set Up Remotes for SpringUserFramework Source: https://github.com/devondragon/springuserframework/blob/main/CONTRIBUTING.md Instructions for forking and cloning the SpringUserFramework and its demo application repositories, and setting up upstream remotes for tracking changes. ```bash git clone https://github.com/your-username/SpringUserFramework.git git clone https://github.com/your-username/SpringUserFrameworkDemoApp.git cd SpringUserFramework git remote add upstream https://github.com/devondragon/SpringUserFramework.git cd ../SpringUserFrameworkDemoApp git remote add upstream https://github.com/devondragon/SpringUserFrameworkDemoApp.git ``` -------------------------------- ### Update Framework Dependency (Maven) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Declares the Spring User Framework dependency with version 4.0.0 in a Maven pom.xml. ```xml com.digitalsanctuary ds-spring-user-framework 4.0.0 ``` -------------------------------- ### Update Spring Boot Plugin Version (Gradle) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Specifies the Spring Boot plugin version to 4.0.0 in a Gradle build file. ```groovy plugins { id 'org.springframework.boot' version '4.0.0' } ``` -------------------------------- ### Custom User Profile Extension (Java) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Illustrates how to extend the framework's user profile management by implementing the `UserProfileService` interface. This allows for the addition of application-specific user data and logic. ```java import org.springframework.stereotype.Service; // Assuming User and CustomUserProfile are defined elsewhere // import com.example.user.User; // import com.example.user.profile.CustomUserProfile; // import com.example.user.profile.UserProfileService; @Service public class CustomUserProfileService implements UserProfileService { @Override public CustomUserProfile getOrCreateProfile(User user) { // Your implementation to get or create a custom user profile // Example: Check if profile exists, if not, create and return a new one System.out.println("Getting or creating profile for user: " + user.getUsername()); // return new CustomUserProfile(); // Placeholder return null; // Replace with actual implementation } @Override public CustomUserProfile updateProfile(CustomUserProfile profile) { // Your implementation to update the custom user profile System.out.println("Updating profile for user: " + profile.getUserId()); // Assuming getUserId() exists // return profile; // Placeholder return null; // Replace with actual implementation } } ``` -------------------------------- ### Run SpringUserFramework Demo App with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/CONTRIBUTING.md Command to run the SpringUserFrameworkDemoApp using Gradle, allowing you to test changes made to the library. ```bash cd ../SpringUserFrameworkDemoApp ./gradlew bootRun ``` -------------------------------- ### Update Framework Dependency (Gradle) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Adds or updates the Spring User Framework dependency to version 4.0.0 in a Gradle build file. ```groovy implementation 'com.digitalsanctuary:ds-spring-user-framework:4.0.0' ``` -------------------------------- ### Configure Email Service (application.yml) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Optional but recommended email configuration for features like password reset and verification. Set your SMTP server details, credentials, and the desired 'from' address for outgoing emails. ```yaml spring: mail: host: smtp.gmail.com 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 ``` -------------------------------- ### Run All Unit Tests with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/CONTRIBUTING.md Command to execute all unit tests for the SpringUserFramework project using Gradle, ensuring code quality and functionality. ```bash ./gradlew test ``` -------------------------------- ### Update SpringUserFramework Dependency in Demo App Source: https://github.com/devondragon/springuserframework/blob/main/CONTRIBUTING.md Example of how to update the SpringUserFramework dependency in the demo application's `build.gradle` file to use the locally published snapshot version. ```groovy // In SpringUserFrameworkDemoApp/build.gradle dependencies { implementation 'com.yourgroupid:spring-user-framework:1.2.3-SNAPSHOT' } ``` -------------------------------- ### Profile Update Endpoint Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Information regarding the changes to the `/user/updateUser` endpoint in version 4.x, including the new request DTO and security improvements. ```APIDOC ## Profile Update Endpoint Changes ### Description The `/user/updateUser` endpoint in version 4.x now accepts `UserProfileUpdateDto` instead of `UserDto`. This change enhances security by removing the need for password fields during profile updates. ### Method POST ### Endpoint `/user/updateUser` ### Parameters #### Request Body - **firstName** (string) - Required - The user's first name. - **lastName** (string) - Required - The user's last name. ### Request Example #### After (4.x) ```json { "firstName": "John", "lastName": "Doe" } ``` #### Before (3.x) - For reference ```json { "email": "user@example.com", "firstName": "John", "lastName": "Doe", "password": "...", "matchingPassword": "..." } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of the update. #### Response Example ```json { "message": "User profile updated successfully." } ``` ### Notes Update your frontend code if you are directly calling this endpoint. ``` -------------------------------- ### Admin Password Reset Programmatically (Java) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Demonstrates how administrators can programmatically initiate password resets for users using the UserEmailService. It shows options for invalidating user sessions and using configured application URLs. Requires ROLE_ADMIN authorization and sends a password reset email with a secure token. ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; // ... other imports public class UserController { @Autowired private UserEmailService userEmailService; // Reset password and invalidate all user sessions @PreAuthorize("hasRole('ROLE_ADMIN')") public int initiateAdminPasswordResetWithSessionInvalidation(User user, String appUrl) { return userEmailService.initiateAdminPasswordReset(user, appUrl, true); } // Reset password without invalidating sessions @PreAuthorize("hasRole('ROLE_ADMIN')") public void initiateAdminPasswordResetWithoutSessionInvalidation(User user, String appUrl) { userEmailService.initiateAdminPasswordReset(user, appUrl, false); } // Use configured appUrl (from user.admin.appUrl property) @PreAuthorize("hasRole('ROLE_ADMIN')") public void initiateAdminPasswordResetWithConfiguredAppUrl(User user) { userEmailService.initiateAdminPasswordReset(user); } } ``` -------------------------------- ### Update Java Version for Spring Boot 4.0 (Maven) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Sets the Java version to 21 or higher in the Maven pom.xml for Spring Boot 4.0 compatibility. ```xml 21 ``` -------------------------------- ### Test Annotation Import Changes Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Updates required for test annotations when migrating from Spring Boot 3.x to 4.x. This includes changes in package locations for common testing annotations. ```APIDOC ## Test Annotation Import Changes ### Description Updates required for test annotations when migrating from Spring Boot 3.x to 4.x. This includes changes in package locations for common testing annotations. ### Method N/A (Code changes) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Examples #### Annotation Package Changes | Annotation | Old Package (3.x) | New Package (4.x) | |---|---|---| | `@AutoConfigureMockMvc` | `org.springframework.boot.test.autoconfigure.web.servlet` | `org.springframework.boot.webmvc.test.autoconfigure` | | `@WebMvcTest` | `org.springframework.boot.test.autoconfigure.web.servlet` | `org.springframework.boot.webmvc.test.autoconfigure` | | `@DataJpaTest` | `org.springframework.boot.test.autoconfigure.orm.jpa` | `org.springframework.boot.data.jpa.test.autoconfigure` | | `@AutoConfigureTestDatabase` | `org.springframework.boot.test.autoconfigure.jdbc` | `org.springframework.boot.jdbc.test.autoconfigure` | #### Example Migration ```java // Before (3.x) import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; // After (4.x) import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; ``` ``` -------------------------------- ### Publish SpringUserFramework Locally with Gradle Source: https://github.com/devondragon/springuserframework/blob/main/CONTRIBUTING.md Command to build and publish the SpringUserFramework library to the local Maven repository using Gradle, enabling local testing with the demo app. ```bash cd SpringUserFramework ./gradlew publishToMavenLocal ``` -------------------------------- ### Migrate Spring Security Configuration (Java) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Demonstrates the migration of Spring Security configuration from deprecated methods like `authorizeRequests()` and `antMatchers()` to `authorizeHttpRequests()` and `requestMatchers()` for Spring Security 7. ```java // Before (3.x) http.authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated(); // After (4.x) http.authorizeHttpRequests(authz -> authz .requestMatchers("/public/**").permitAll() .anyRequest().authenticated()); ``` -------------------------------- ### Update Security Configuration URL Patterns (YAML) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Modifies unprotected URIs in Spring User Framework configuration to include leading slashes for Spring Security 7 compatibility. ```yaml user: security: unprotectedURIs: /,/index.html,/css/**,/js/**,/error,/error.html ``` -------------------------------- ### Register New User (REST API) Source: https://context7.com/devondragon/springuserframework/llms.txt Registers a new user account via a POST request to `/user/registration`. It enforces validation and password policies. The response includes success status, a code, a message, and a redirect URL. Error responses indicate issues like existing accounts or password policy violations. ```bash # Register a new user curl -X POST http://localhost:8080/user/registration \ -H "Content-Type: application/json" \ -H "X-CSRF-TOKEN: " \ -d '{ "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "password": "SecureP@ss123", "matchingPassword": "SecureP@ss123" }' # Success Response (200 OK) { "success": true, "code": 0, "message": "Registration Successful!", "redirectUrl": "/user/registration-success.html" } # Error Response - User Already Exists (409 Conflict) { "success": false, "code": 2, "message": "An account already exists for the email address" } # Error Response - Password Policy Violation (400 Bad Request) { "success": false, "code": 1, "message": "Password must contain at least one uppercase letter. Password must be at least 8 characters." } ``` -------------------------------- ### Update Java Version for Spring Boot 4.0 (Gradle) Source: https://github.com/devondragon/springuserframework/blob/main/MIGRATION.md Configures the Java toolchain to use Java 21 or higher for Spring Boot 4.0 applications using Gradle. ```groovy java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } ``` -------------------------------- ### Create User Profile Extension (Java) Source: https://github.com/devondragon/springuserframework/blob/main/README.md An optional Java class extending `BaseUserProfile` to add custom fields to the user profile. This allows for storing additional application-specific user data. ```java @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 } ``` -------------------------------- ### Add Spring User Framework Dependencies (Maven & Gradle) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Includes the main framework dependency for Spring Boot 4.0 (Java 21+) or Spring Boot 3.5 (Java 17+), along with essential Spring Boot starters for Thymeleaf, Mail, JPA, Security, and Spring Retry. These are crucial for the framework's functionality. ```groovy implementation 'com.digitalsanctuary:ds-spring-user-framework:4.0.2' // For Spring Boot 3.5 (Java 17+): implementation 'com.digitalsanctuary:ds-spring-user-framework:3.5.1' ``` ```xml org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-mail org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-security org.springframework.retry spring-retry ``` ```groovy 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.retry:spring-retry' ``` -------------------------------- ### Keycloak SSO OIDC Configuration (YAML) Source: https://github.com/devondragon/springuserframework/blob/main/README.md Details the YAML configuration for enabling Single Sign-On (SSO) with Keycloak using OpenID Connect (OIDC). This includes client registration, provider details, and user name attributes, often used in Docker environments. ```yaml 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} ```