backend\src\main\java\com\mechanical\erp\config\SecurityConfig.java
是一个 Java 配置文件,用于配置 Spring Security。Spring Security 是一个强大的安全框架,用于保护应用程序的安全性,包括身份验证、授权、会话管理等功能。
文件路径
backend\src\main\java\com\mechanical\erp\config\SecurityConfig.java
文件内容
以下是一个典型的 SecurityConfig.java
文件的示例,展示了如何配置 Spring Security:
java">package com.mechanical.erp.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;import com.mechanical.erp.common.security.service.UserDetailsServiceImpl;
import com.mechanical.erp.common.security.jwt.AuthEntryPointJwt;
import com.mechanical.erp.common.security.jwt.AuthTokenFilter;@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredUserDetailsServiceImpl userDetailsService;@Autowiredprivate AuthEntryPointJwt unauthorizedHandler;@Beanpublic AuthTokenFilter authenticationJwtTokenFilter() {return new AuthTokenFilter();}@Overridepublic void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/api/auth/**").permitAll().anyRequest().authenticated();http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);}
}
解释
1. 包声明
java">package com.mechanical.erp.config;
这行代码声明了该类所在的包路径。
2. 导入语句
java">import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;import com.mechanical.erp.common.security.service.UserDetailsServiceImpl;
import com.mechanical.erp.common.security.jwt.AuthEntryPointJwt;
import com.mechanical.erp.common.security.jwt.AuthTokenFilter;
这些导入语句引入了必要的 Spring Security 类和自定义服务类。
3. 类声明
java">@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Configuration: 表明该类可以提供 Spring 配置。
- @EnableWebSecurity: 启用 Spring Security 的 Web 安全支持。
- @EnableGlobalMethodSecurity(prePostEnabled = true): 启用方法级别的安全性注解(如
@PreAuthorize
,@PostAuthorize
等)。 - extends WebSecurityConfigurerAdapter: 继承
WebSecurityConfigurerAdapter
以自定义安全配置。
4. 自动注入依赖
java">@Autowired
UserDetailsServiceImpl userDetailsService;@Autowired
private AuthEntryPointJwt unauthorizedHandler;
- UserDetailsServiceImpl: 实现用户详细信息服务。
- AuthEntryPointJwt: 处理未经授权的请求。
5. Bean 定义
java">@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {return new AuthTokenFilter();
}@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();
}@Bean
public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();
}
- AuthTokenFilter: JWT 过滤器,用于处理 JWT 认证。
- AuthenticationManager: 提供认证管理器 bean。
- PasswordEncoder: 密码编码器,使用 BCrypt 加密密码。
6. 配置认证管理器
java">@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
- configure(AuthenticationManagerBuilder): 配置认证管理器,使用
UserDetailsServiceImpl
和BCryptPasswordEncoder
。
7. 配置 HTTP 安全
java">@Override
protected void configure(HttpSecurity http) throws Exception {http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/api/auth/**").permitAll().anyRequest().authenticated();http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
- cors().and().csrf().disable(): 禁用 CORS 和 CSRF 保护。
- exceptionHandling().authenticationEntryPoint(unauthorizedHandler): 设置未授权处理器。
- sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS): 使用无状态会话管理。
- authorizeRequests().antMatchers("/api/auth/").permitAll()**: 允许
/api/auth/**
路径下的所有请求。 - anyRequest().authenticated(): 其他所有请求需要认证。
- addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class): 在
UsernamePasswordAuthenticationFilter
之前添加 JWT 过滤器。
示例解释
以下是一个更详细的 SecurityConfig.java
文件示例,包含更多的配置选项:
java">package com.mechanical.erp.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;import com.mechanical.erp.common.security.service.UserDetailsServiceImpl;
import com.mechanical.erp.common.security.jwt.AuthEntryPointJwt;
import com.mechanical.erp.common.security.jwt.AuthTokenFilter;@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredUserDetailsServiceImpl userDetailsService;@Autowiredprivate AuthEntryPointJwt unauthorizedHandler;@Beanpublic AuthTokenFilter authenticationJwtTokenFilter() {return new AuthTokenFilter();}@Overridepublic void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/api/auth/**").permitAll().antMatchers("/api/test/**").permitAll().anyRequest().authenticated();http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);}
}