Spring Security configuration

This commit is contained in:
myh 2023-12-03 23:40:45 +08:00
parent 7bf3e22ee6
commit cf3d50c6d9
2 changed files with 14 additions and 8 deletions

View File

@ -4,6 +4,8 @@ import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@ -12,18 +14,21 @@ import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity // Enable Spring Security
public class DefaultSecurityConfigure {
@EnableGlobalAuthentication // Enable Spring Security's global authentication configuration
@EnableMethodSecurity(prePostEnabled = true) // Enable Spring Security's method security
public class SecurityConfig {
@Bean
public SecurityFilterChain defaultSecurityFilterChain(@NotNull HttpSecurity http) throws Exception {
var ignoreUrls = new String[]{""};
var authedUrls = new String[]{"/users"};
http.authorizeHttpRequests(
(req) -> req.requestMatchers(ignoreUrls).permitAll()
)
public SecurityFilterChain SecurityFilterChain(@NotNull HttpSecurity http) throws Exception {
var ignoreUrls = new String[]{"/login", "/logout", "/error"};
var authedUrls = new String[]{"/users/*/**"};
http
.authorizeHttpRequests(
(req) -> req.requestMatchers(authedUrls).authenticated()
(request) -> request
.requestMatchers(authedUrls).authenticated() // authenticate all requests to authedUrls
.requestMatchers(ignoreUrls).permitAll() // permit all requests to ignoreUrls
)
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.logout(LogoutConfigurer::permitAll);
return http.build();

View File

@ -14,6 +14,7 @@ spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
# spring security config
spring.security.user.name=anchor
spring.security.user.password=20172