From 7530255b96d8db91a17832915c7d2fe1290da722 Mon Sep 17 00:00:00 2001 From: Nhat-Original Date: Thu, 2 May 2024 23:37:22 +0700 Subject: [PATCH] fix: replace Iterable with List, fix @PreAuthorize --- doc/example-feature/TaskController.java | 2 +- doc/example-feature/TaskService.java | 2 +- .../spring/config/SecurityConfig.java | 119 +++++++++--------- .../spring/controller/MenuItemController.java | 3 +- .../spring/security/CustomUserDetails.java | 82 ++++++------ .../spring/service/MenuItemService.java | 4 +- 6 files changed, 109 insertions(+), 103 deletions(-) diff --git a/doc/example-feature/TaskController.java b/doc/example-feature/TaskController.java index b68d966..bfc86ad 100644 --- a/doc/example-feature/TaskController.java +++ b/doc/example-feature/TaskController.java @@ -14,7 +14,7 @@ public class TaskController { private TaskService taskService; @GetMapping - public Iterable getTaskList() { + public List getTaskList() { return taskService.getTaskList(); } diff --git a/doc/example-feature/TaskService.java b/doc/example-feature/TaskService.java index 35ba636..99e8566 100644 --- a/doc/example-feature/TaskService.java +++ b/doc/example-feature/TaskService.java @@ -9,7 +9,7 @@ public class TaskService { @Autowired private TaskRepository taskRepository; - public Iterable getTaskList() { + public List getTaskList() { return taskRepository.findAll(); } diff --git a/src/main/java/com/github/nhatoriginal/spring/config/SecurityConfig.java b/src/main/java/com/github/nhatoriginal/spring/config/SecurityConfig.java index 514e5a9..e4a93d8 100644 --- a/src/main/java/com/github/nhatoriginal/spring/config/SecurityConfig.java +++ b/src/main/java/com/github/nhatoriginal/spring/config/SecurityConfig.java @@ -1,4 +1,5 @@ package com.github.nhatoriginal.spring.config; + import org.springframework.http.HttpMethod; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.Customizer; @@ -34,68 +35,70 @@ @Configuration @EnableWebSecurity @RequiredArgsConstructor -@EnableMethodSecurity +@EnableMethodSecurity(prePostEnabled = true) public class SecurityConfig { - private final JwtAuthenticationFilter jwtAuthFilter; - private final UserService userService; - @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationProvider authenticationProvider) throws Exception { - return http - .cors(corsConfigurationSource()) - .securityMatcher("/api/**") - .authorizeHttpRequests(req -> - req.requestMatchers("/api/v1/auth/**") - .permitAll() - .anyRequest() - .authenticated() - ) - .sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) - .authenticationProvider(authenticationProvider) - .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) - .logout(logout -> - logout.logoutUrl("/api/v1/auth/logout")).build(); - } + private final JwtAuthenticationFilter jwtAuthFilter; + private final UserService userService; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationProvider authenticationProvider) + throws Exception { + return http + .cors(corsConfigurationSource()) + .securityMatcher("/api/**") + .authorizeHttpRequests(req -> req.requestMatchers("/api/v1/auth/**") + .permitAll() + .anyRequest() + .authenticated()) + .sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) + .authenticationProvider(authenticationProvider) + .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) + .logout(logout -> logout.logoutUrl("/api/v1/auth/logout")).build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - @Bean - public Customizer> corsConfigurationSource() { - return cors -> { - CorsConfiguration configuration = new CorsConfiguration(); - configuration.setAllowedOrigins(List.of("*")); - configuration.setAllowedMethods(Arrays.asList( - HttpMethod.GET.name(), - HttpMethod.HEAD.name(), - HttpMethod.POST.name(), - HttpMethod.PUT.name(), - HttpMethod.DELETE.name(), - HttpMethod.OPTIONS.name(), - HttpMethod.PATCH.name() - ) + @Bean + public Customizer> corsConfigurationSource() { + return cors -> { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(List.of("*")); + configuration.setAllowedMethods(Arrays.asList( + HttpMethod.GET.name(), + HttpMethod.HEAD.name(), + HttpMethod.POST.name(), + HttpMethod.PUT.name(), + HttpMethod.DELETE.name(), + HttpMethod.OPTIONS.name(), + HttpMethod.PATCH.name()) + ); + configuration.setAllowedHeaders(List.of("Authorization ", "Cache-Control", "Content-Type", "Origin", "Accept", + "X-Requested-With", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", + "Access-Control-Request-Method", "Access-Control-Request-Headers", "Access-Control-Allow-Credentials", + "Access-Control-Expose-Headers", "Access-Control-Max-Age")); + configuration.setAllowCredentials(true); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + cors.configurationSource(source); + }; + } - ); - configuration.setAllowedHeaders(List.of("Authorization ", "Cache-Control", "Content-Type", "Origin", "Accept", "X-Requested-With", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Access-Control-Request-Method", "Access-Control-Request-Headers", "Access-Control-Allow-Credentials", "Access-Control-Expose-Headers", "Access-Control-Max-Age")); - configuration.setAllowCredentials(true); - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", configuration); - cors.configurationSource(source); - }; - } - @Bean - public AuthenticationProvider authenticationProvider(PasswordEncoder passwordEncoder) { - DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(userService); - authProvider.setPasswordEncoder(passwordEncoder); - return authProvider; - } + @Bean + public AuthenticationProvider authenticationProvider(PasswordEncoder passwordEncoder) { + DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(userService); + authProvider.setPasswordEncoder(passwordEncoder); + return authProvider; + } - @Bean - public AuthenticationManager authenticationManager(AuthenticationConfiguration config) - throws Exception { - return config.getAuthenticationManager(); - } + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration config) + throws Exception { + return config.getAuthenticationManager(); + } } diff --git a/src/main/java/com/github/nhatoriginal/spring/controller/MenuItemController.java b/src/main/java/com/github/nhatoriginal/spring/controller/MenuItemController.java index 5307a1b..751e995 100644 --- a/src/main/java/com/github/nhatoriginal/spring/controller/MenuItemController.java +++ b/src/main/java/com/github/nhatoriginal/spring/controller/MenuItemController.java @@ -1,5 +1,6 @@ package com.github.nhatoriginal.spring.controller; +import java.util.List; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; @@ -17,7 +18,7 @@ public class MenuItemController { private MenuItemService menuItemService; @GetMapping(Endpoint.MenuItem.GET_ALL) - public Iterable getMenuItemList() { + public List getMenuItemList() { return menuItemService.getMenuItemList(); } diff --git a/src/main/java/com/github/nhatoriginal/spring/security/CustomUserDetails.java b/src/main/java/com/github/nhatoriginal/spring/security/CustomUserDetails.java index d6d92ba..e945501 100644 --- a/src/main/java/com/github/nhatoriginal/spring/security/CustomUserDetails.java +++ b/src/main/java/com/github/nhatoriginal/spring/security/CustomUserDetails.java @@ -1,4 +1,5 @@ package com.github.nhatoriginal.spring.security; + import org.springframework.security.core.authority.SimpleGrantedAuthority; import com.github.nhatoriginal.spring.model.User; import org.springframework.security.core.GrantedAuthority; @@ -8,45 +9,44 @@ import java.util.Collections; public class CustomUserDetails implements UserDetails { - private final User user; - - public CustomUserDetails(User user) { - this.user = user; - } - - @Override - public Collection getAuthorities() { - return Collections.singleton(new SimpleGrantedAuthority(user.getRole().name())); - } - - - @Override - public String getPassword() { - return user.getHashedPassword(); - } - - @Override - public String getUsername() { - return user.getEmail(); - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } + private final User user; + + public CustomUserDetails(User user) { + this.user = user; + } + + @Override + public Collection getAuthorities() { + return Collections.singleton(new SimpleGrantedAuthority("ROLE_" + user.getRole().name())); + } + + @Override + public String getPassword() { + return user.getHashedPassword(); + } + + @Override + public String getUsername() { + return user.getEmail(); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } } \ No newline at end of file diff --git a/src/main/java/com/github/nhatoriginal/spring/service/MenuItemService.java b/src/main/java/com/github/nhatoriginal/spring/service/MenuItemService.java index 932bc93..5bd355a 100644 --- a/src/main/java/com/github/nhatoriginal/spring/service/MenuItemService.java +++ b/src/main/java/com/github/nhatoriginal/spring/service/MenuItemService.java @@ -5,6 +5,8 @@ import org.springframework.web.server.ResponseStatusException; import com.github.nhatoriginal.spring.model.MenuItem; import com.github.nhatoriginal.spring.repository.MenuItemRepository; + +import java.util.List; import java.util.UUID; import org.springframework.http.HttpStatus; @@ -13,7 +15,7 @@ public class MenuItemService { @Autowired private MenuItemRepository menuItemRepository; - public Iterable getMenuItemList() { + public List getMenuItemList() { return menuItemRepository.findAll(); }