springboot3 使用 spring-security 做安全验证。
引入 pom
1
2
3
4
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
|
再 config 中配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer {
// @Value("${spring.security.user.name}")
// private String username;
//
// @Value("${spring.security.user.password}")
// private String password;
private final String adminContextPath;
public WebSecurityConfigurer(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
/**
* spring security 默认的安全策略
* @param http security注入点
* @return SecurityFilterChain
* @throws Exception
*/
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
//
// http.headers().frameOptions().disable().and().authorizeRequests()
// .requestMatchers(adminContextPath + "/assets/**", adminContextPath + "/login",
// adminContextPath + "/actuator/**")
// .permitAll().dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll().anyRequest().authenticated().and()
// .formLogin().loginPage(adminContextPath +
// "/login").successHandler(successHandler).and().logout()
// .logoutUrl(adminContextPath +
// "/logout").and().httpBasic().and().csrf().disable();
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests //
.requestMatchers(new AntPathRequestMatcher(adminContextPath + "/assets/**")).permitAll()
.requestMatchers(new AntPathRequestMatcher(adminContextPath + "/variables.css")).permitAll()
.requestMatchers(new AntPathRequestMatcher(adminContextPath + "/actuator/info")).permitAll()
.requestMatchers(new AntPathRequestMatcher(adminContextPath + "/actuator/health")).permitAll()
.requestMatchers(new AntPathRequestMatcher(adminContextPath + "/login")).permitAll()
.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll() // https://github.com/spring-projects/spring-security/issues/11027
.anyRequest().authenticated())
.formLogin(
(formLogin) -> formLogin.loginPage(adminContextPath + "/login").successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(adminContextPath + "/logout"))
.httpBasic(Customizer.withDefaults());
http.addFilterAfter(new CustomCsrfFilter(), BasicAuthenticationFilter.class)
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()).ignoringRequestMatchers(
new AntPathRequestMatcher(adminContextPath + "/instances", POST.toString()),
new AntPathRequestMatcher(adminContextPath + "/instances/*", DELETE.toString()),
new AntPathRequestMatcher(adminContextPath + "/actuator/**")));
http.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
return http.build();
}
// @Bean
// public UserDetailsService userDetailsService() {
// UserDetails user =
// User.withDefaultPasswordEncoder().username(username).password(password).roles("USER")
// .build();
//
// return new InMemoryUserDetailsManager(user);
// }
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/js/**", "/images/**");
}
|
踩坑 401 之旅:
访问 login 之后,出现了/applicaitons 报错 401.
参考文档:
Spring Boot Admin – (spring-boot-admin.com)
https://www.bezkoder.com/websecurityconfigureradapter-deprecated-spring-boot/
https://yanbin.blog/springboot-security-jwt-token-how-to-abcs/
参考文档:
https://spring.io/guides/gs/securing-web/