22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame^] | 1 | package com.example.myproject.config; |
| 2 | |
| 3 | import org.springframework.beans.factory.annotation.Autowired; |
| 4 | import org.springframework.context.annotation.Bean; |
| 5 | import org.springframework.security.authentication.AuthenticationManager; |
| 6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; |
| 7 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; |
| 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| 9 | import org.springframework.security.config.annotation.web.builders.WebSecurity; |
| 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; |
| 12 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; |
| 13 | import org.springframework.security.crypto.password.PasswordEncoder; |
| 14 | |
| 15 | @EnableWebSecurity //注解开启Spring Security的功能 |
| 16 | public class SecurityConfig extends WebSecurityConfigurerAdapter { |
| 17 | |
| 18 | @Bean |
| 19 | public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { |
| 20 | return authenticationConfiguration.getAuthenticationManager(); |
| 21 | } |
| 22 | @Bean |
| 23 | public PasswordEncoder passwordEncoder() { |
| 24 | return new BCryptPasswordEncoder();//passwordEncoder的实现类 |
| 25 | } |
| 26 | |
| 27 | //构造一个内存框架对象,获取数据库中的数据 |
| 28 | /* @Bean |
| 29 | public UserDetailsService myUserDetailsService(){ |
| 30 | return new TestUserServerImpl(); |
| 31 | }*/ |
| 32 | //也可以自动注入 |
| 33 | |
| 34 | //用户授权 |
| 35 | |
| 36 | |
| 37 | //用户权限认证 |
| 38 | @Override |
| 39 | protected void configure(HttpSecurity http) throws Exception { |
| 40 | http |
| 41 | .csrf().disable() // 禁用 CSRF 保护 |
| 42 | .authorizeRequests() |
| 43 | .antMatchers("/swagger-ui.html", "/webjars/**", "/v2/**", "/swagger-resources/**","/**").permitAll() // 允许无条件访问 |
| 44 | .anyRequest().authenticated(); // 其他所有路径都需要身份验证 |
| 45 | } |
| 46 | |
| 47 | |
| 48 | /** |
| 49 | * 核心过滤器配置,更多使用ignoring()用来忽略对静态资源的控制 |
| 50 | */ |
| 51 | @Override |
| 52 | public void configure(WebSecurity web) throws Exception { |
| 53 | web |
| 54 | .ignoring() |
| 55 | .antMatchers("/image/**"); |
| 56 | } |
| 57 | } |