-
Notifications
You must be signed in to change notification settings - Fork 0
feat(springSecurity): add spring security in app #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1df5da2
feat(springSecurity): add spring security in app
Theo-lbg 339e7ee
feat(security): enhance security configuration with multiple user rol…
Theo-lbg ea7f383
feat(test): refactor authentication to use values from application pr…
Theo-lbg e856fe6
feat(security): enhance security filter chain and add custom exceptio…
Theo-lbg f7bddb9
feat(springSecurity): add spring security in app
MayuriXx b80f964
fix(addSpace): space
Theo-lbg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
src/main/java/com/xpeho/spring_boot_java_random_user/config/SecurityConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| package com.xpeho.spring_boot_java_random_user.config; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.http.HttpMethod; | ||
| import org.springframework.security.core.userdetails.User; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.security.core.userdetails.UserDetailsService; | ||
| import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.config.Customizer; | ||
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
| import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
| import org.springframework.security.config.http.SessionCreationPolicy; | ||
| import org.springframework.security.provisioning.InMemoryUserDetailsManager; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.security.web.context.NullSecurityContextRepository; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
| public class SecurityConfig { | ||
|
|
||
| private static final String RANDOM_USERS_PATH = "/random-users/**"; | ||
| private static final String RANDOM_USERS_PREFIX = "/random-users"; | ||
| private static final String ADMIN_ROLE = "ADMIN"; | ||
|
|
||
| @Value("${app.security.admin.username}") | ||
| private String adminUsername; | ||
|
|
||
| @Value("${app.security.admin.password}") | ||
| private String adminPassword; | ||
|
|
||
| @Value("${app.security.user.username}") | ||
| private String userUsername; | ||
|
|
||
| @Value("${app.security.user.password}") | ||
| private String userPassword; | ||
|
|
||
| @Value("${app.security.test.username}") | ||
| private String testUsername; | ||
|
|
||
| @Value("${app.security.test.password}") | ||
| private String testPassword; | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain securityFilterChain(HttpSecurity http) { | ||
| try { | ||
| return http | ||
| .csrf(csrf -> csrf.ignoringRequestMatchers(this::isBasicAuthRequest)) | ||
| .securityContext(context -> context.securityContextRepository(new NullSecurityContextRepository())) | ||
|
Theo-lbg marked this conversation as resolved.
|
||
| .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | ||
| .httpBasic(Customizer.withDefaults()) | ||
| .authorizeHttpRequests(auth -> auth | ||
| .requestMatchers(getPublicEndpoints()).permitAll() | ||
| .requestMatchers(HttpMethod.GET, RANDOM_USERS_PATH).hasAnyRole(ADMIN_ROLE, "USER", "TEST") | ||
|
Theo-lbg marked this conversation as resolved.
|
||
| .requestMatchers(HttpMethod.POST, RANDOM_USERS_PATH).hasRole(ADMIN_ROLE) | ||
| .requestMatchers(HttpMethod.PUT, RANDOM_USERS_PATH).hasRole(ADMIN_ROLE) | ||
| .requestMatchers(HttpMethod.DELETE, RANDOM_USERS_PATH).hasRole(ADMIN_ROLE) | ||
|
MayuriXx marked this conversation as resolved.
Comment on lines
+58
to
+61
|
||
| .anyRequest().authenticated() | ||
| ) | ||
| .build(); | ||
| } catch (Exception e) { | ||
| throw new SecurityConfigurationException("Failed to build Spring Security filter chain", e); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| private boolean isBasicAuthRequest(HttpServletRequest request) { | ||
| String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); | ||
| String servletPath = request.getServletPath(); | ||
| boolean isRandomUsersPath = servletPath != null && servletPath.startsWith(RANDOM_USERS_PREFIX); | ||
| return isRandomUsersPath && authHeader != null && authHeader.startsWith("Basic "); | ||
| } | ||
|
|
||
| private String[] getPublicEndpoints() { | ||
| return new String[]{ | ||
| "/api/**", | ||
| "/swagger-ui/**", | ||
| "/swagger-ui.html", | ||
| "/v3/api-docs/**", | ||
| "/actuator/health" | ||
| }; | ||
| } | ||
|
|
||
| @Bean | ||
| UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) { | ||
|
Theo-lbg marked this conversation as resolved.
|
||
| UserDetails admin = User.withUsername(adminUsername) | ||
| .password(passwordEncoder.encode(adminPassword)) | ||
| .roles(ADMIN_ROLE) | ||
| .build(); | ||
|
|
||
| UserDetails user = User.withUsername(userUsername) | ||
| .password(passwordEncoder.encode(userPassword)) | ||
| .roles("USER") | ||
| .build(); | ||
|
|
||
| UserDetails test = User.withUsername(testUsername) | ||
| .password(passwordEncoder.encode(testPassword)) | ||
| .roles("TEST") | ||
| .build(); | ||
|
|
||
| return new InMemoryUserDetailsManager(admin, user, test); | ||
| } | ||
|
|
||
| @Bean | ||
| PasswordEncoder passwordEncoder() { | ||
|
Theo-lbg marked this conversation as resolved.
|
||
| return new BCryptPasswordEncoder(); | ||
| } | ||
| } | ||
8 changes: 8 additions & 0 deletions
8
...in/java/com/xpeho/spring_boot_java_random_user/config/SecurityConfigurationException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| package com.xpeho.spring_boot_java_random_user.config; | ||
|
|
||
| public class SecurityConfigurationException extends RuntimeException { | ||
|
|
||
| public SecurityConfigurationException(String message, Throwable cause) { | ||
| super(message, cause); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
129 changes: 129 additions & 0 deletions
129
src/test/java/com/xpeho/spring_boot_java_random_user/config/SecurityConfigTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| package com.xpeho.spring_boot_java_random_user.config; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.springframework.mock.web.MockHttpServletRequest; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.security.core.userdetails.UserDetailsService; | ||
| import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.test.util.ReflectionTestUtils; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.assertj.core.api.Assertions.assertThatThrownBy; | ||
| import static org.mockito.Mockito.mock; | ||
| import static org.mockito.Mockito.when; | ||
|
|
||
| class SecurityConfigTest { | ||
|
|
||
| private final SecurityConfig securityConfig = new SecurityConfig(); | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| ReflectionTestUtils.setField(securityConfig, "adminUsername", "admin"); | ||
| ReflectionTestUtils.setField(securityConfig, "adminPassword", "admin123"); | ||
| ReflectionTestUtils.setField(securityConfig, "userUsername", "apiuser"); | ||
| ReflectionTestUtils.setField(securityConfig, "userPassword", "changeit"); | ||
| ReflectionTestUtils.setField(securityConfig, "testUsername", "testuser"); | ||
| ReflectionTestUtils.setField(securityConfig, "testPassword", "testpass"); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldEncodePasswordsWithBcrypt() { | ||
| PasswordEncoder passwordEncoder = securityConfig.passwordEncoder(); | ||
|
|
||
| assertThat(passwordEncoder).isInstanceOf(BCryptPasswordEncoder.class); | ||
| assertThat(passwordEncoder.matches("admin123", passwordEncoder.encode("admin123"))).isTrue(); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldCreateInMemoryUsersWithExpectedRoles() { | ||
| PasswordEncoder passwordEncoder = securityConfig.passwordEncoder(); | ||
|
|
||
| UserDetailsService userDetailsService = securityConfig.userDetailsService(passwordEncoder); | ||
|
|
||
| UserDetails admin = userDetailsService.loadUserByUsername("admin"); | ||
| UserDetails user = userDetailsService.loadUserByUsername("apiuser"); | ||
| UserDetails test = userDetailsService.loadUserByUsername("testuser"); | ||
|
|
||
| assertThat(admin.getAuthorities()).extracting("authority").containsExactly("ROLE_ADMIN"); | ||
| assertThat(user.getAuthorities()).extracting("authority").containsExactly("ROLE_USER"); | ||
| assertThat(test.getAuthorities()).extracting("authority").containsExactly("ROLE_TEST"); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldRecognizeBasicAuthRequestsOnRandomUsersPath() { | ||
| MockHttpServletRequest request = new MockHttpServletRequest(); | ||
| request.setServletPath("/random-users/123"); | ||
| request.addHeader("Authorization", "Basic dGVzdDp0ZXN0"); | ||
|
|
||
| boolean result = ReflectionTestUtils.invokeMethod(securityConfig, "isBasicAuthRequest", request); | ||
|
|
||
| assertThat(result).isTrue(); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldRejectNonBasicAuthOrNonRandomUsersRequests() { | ||
| MockHttpServletRequest request = new MockHttpServletRequest(); | ||
| request.setServletPath("/health"); | ||
| request.addHeader("Authorization", "Bearer token"); | ||
|
|
||
| boolean result = ReflectionTestUtils.invokeMethod(securityConfig, "isBasicAuthRequest", request); | ||
|
|
||
| assertThat(result).isFalse(); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldRejectRandomUsersRequestWithoutAuthHeader() { | ||
| MockHttpServletRequest request = new MockHttpServletRequest(); | ||
| request.setServletPath("/random-users/123"); | ||
|
|
||
| boolean result = ReflectionTestUtils.invokeMethod(securityConfig, "isBasicAuthRequest", request); | ||
|
|
||
| assertThat(result).isFalse(); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldRejectRandomUsersRequestWithNonBasicAuthHeader() { | ||
| MockHttpServletRequest request = new MockHttpServletRequest(); | ||
| request.setServletPath("/random-users/123"); | ||
| request.addHeader("Authorization", "Bearer token"); | ||
|
|
||
| boolean result = ReflectionTestUtils.invokeMethod(securityConfig, "isBasicAuthRequest", request); | ||
|
|
||
| assertThat(result).isFalse(); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldRejectWhenServletPathIsNull() { | ||
| HttpServletRequest request = mock(HttpServletRequest.class); | ||
| when(request.getServletPath()).thenReturn(null); | ||
| when(request.getHeader("Authorization")).thenReturn("Basic dGVzdDp0ZXN0"); | ||
|
|
||
| boolean result = ReflectionTestUtils.invokeMethod(securityConfig, "isBasicAuthRequest", request); | ||
|
|
||
| assertThat(result).isFalse(); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldExposePublicEndpoints() { | ||
| String[] endpoints = ReflectionTestUtils.invokeMethod(securityConfig, "getPublicEndpoints"); | ||
|
|
||
| assertThat(endpoints).contains( | ||
| "/api/**", | ||
| "/swagger-ui/**", | ||
| "/swagger-ui.html", | ||
| "/v3/api-docs/**", | ||
| "/actuator/health" | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldWrapFilterChainConfigurationException() { | ||
| assertThatThrownBy(() -> securityConfig.securityFilterChain(null)) | ||
| .isInstanceOf(SecurityConfigurationException.class) | ||
| .hasMessage("Failed to build Spring Security filter chain") | ||
| .hasCauseInstanceOf(NullPointerException.class); | ||
| } | ||
| } |
18 changes: 18 additions & 0 deletions
18
...ava/com/xpeho/spring_boot_java_random_user/config/SecurityConfigurationExceptionTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package com.xpeho.spring_boot_java_random_user.config; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| class SecurityConfigurationExceptionTest { | ||
|
|
||
| @Test | ||
| void shouldExposeMessageAndCause() { | ||
| IllegalStateException cause = new IllegalStateException("boom"); | ||
| SecurityConfigurationException exception = new SecurityConfigurationException("Failed to build Spring Security filter chain", cause); | ||
|
|
||
| assertThat(exception) | ||
| .hasMessage("Failed to build Spring Security filter chain") | ||
| .hasCause(cause); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.