Spring Security之前后端分离
大纲
多余介绍自行官网,这里梳理下大纲,你会学到…:
1.认证流程(如何一步一步完成链路调用)
2.整体集成项目配置(自定义认证器、拦截URL认证、异常处理、会话保存等)
3.如何做资源鉴权处理
认证流程
Spring Security只是一个框架,提供程序身份验证和鉴权,基于Spring基础,强大之处可以自由自定义要求。

认证流程
- 提交用户名、密码请求。
- UsernamePasswordAuthenticationFilter 拦截器将用户名密码封装成Authentication对象。
- AuthenticationManager接口调用authenticate()方法进行认证,该接口实现类ProviderManager调用重写authenticate()方法进行认证。抽象类AbstractUserDetailsAuthenticationProvider中重写了authenticate()。
- AbstractUserDetailsAuthenticationProvider抽象类authenticate()方法中调用retrieveUser()方法。
- DaoAuthenticationProvider中retrieveUser()调用loadUserByUsername()获取用户信息,返回UserDetails对象。
- 比对密码,成功返回Authentication对象,并放入内存,返回给前端。
上面步骤二、三、四、五涉及到封装Authentication对象、authenticate()、loadUserByUsername() 都可以自定义,按照自己业务逻辑进行认证放行还是拒绝,实现灵活自由化扩展。
整体集成项目配置
自定义认证器
认证流程中提到authenticate()方法进行认证,AuthenticationProvider接口和AuthenticationManager接口都有 authenticate() 这个。AuthenticationManager是个顶层接口,子类实现ProviderManager类包含authenticate()方法,for循环AuthenticationProvider实现类调用它authenticate()方法。
所以我们只需要实现AuthenticationProvider接口,重写authenticate()方法,完成我们自己逻辑认证。
/**
* 自定义认证逻辑
*/
@Component
public class CustomerAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 验证登陆认证逻辑
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//用户名
String name = authentication.getName();
//密码
String password = authentication.getCredentials().toString();
//查找用户
User oldUser = userService.findUserByUserName(name);
//比对密码
boolean loginResult = passwordEncoder.matches(password, oldUser.getPassword());
if (loginResult) {
//封装信息返回
UserDetails userDetails = userService.loadUser(name);
//注意这里password 是未加密 userDetails 中 password 已加密的
return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
}
throw new AuthenticationException("登陆失败"){};
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
自定义UserDetailsService接口loadUserByUsername方法
实现UserDetailsService接口,重写loadUserByUsername方法即可
@Service
public class UserServiceImpl implements UserService, UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserMapper userMapper;
@Autowired
private AuthenticationManager authenticationManager;
public int saveUser(User user) {
user.setPassword(this.passwordEncoder.encode(user.getPassword()));
int result = userMapper.saveUser(user);
return result;
}
public UserInfo login(LoginUserDTO userDTO) {
//使用security框架自带的验证token生成器 也可以自定义。
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDTO.getUserName(), userDTO.getPassword());
Authentication authenticate = authenticationManager.authenticate(token);
//放入Security上下文
SecurityContextHolder.getContext().setAuthentication(authenticate);
//获取登陆信息
UserInfo userInfo = (UserInfo) authenticate.getPrincipal();
return userInfo;
}
public User findUserByUserName(String userName) {
return userMapper.findUserByUserName(userName);
}
@Override
public UserDetails loadUser(String username) {
return this.loadUserByUsername(username);
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("loadUserByUsername start>>>>");
User user = this.findUserByUserName(username);
if (Objects.isNull(user)) {
System.out.println("未查询到User用户");
}
//可以自定义实现封装返回参数 implements UserDetails 即可 这里使用框架自带Users
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("sys:menu:add");
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(authority);
//这里封装UserInfo继承User 权限自定义了
UserInfo userInfo=new UserInfo(username, user.getPassword(), authorities);
return userInfo;
}
}
拦截URL认证
- 配置URL资源链接,等同于哪些URL放行,哪些URL需要验证是否登陆。
- Spring Security非最新版2.7.x ,如果使用时最新版这里WebSecurityConfigurerAdapter 是过时的,解决方法
使用 SecurityFilterChain Bean 来配置 HttpSecurity
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
}
使用 WebSecurityCustomizer Bean 来配置 WebSecurity 这个用来配置静态资源CSS、JS等 前后端分离不用配置。
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
//WebSecurityCustomizer 函数接口
return web -> web.ignoring().antMatchers("/login");
}
非2.7.x 版本配置 Security 配置类
/**
* Security 配置类
* 1.加入编码解码器
* 2.自定义登陆认证 authenticationManager.authenticate会进入它
* 3.请求过滤和授权配置
* 4.加入AuthenticationManager管理器
* */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private CustomerAuthenticationProvider customerAuthenticationProvider;
/**
* 加密器
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 自定义登陆认证器
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customerAuthenticationProvider);
//自定义获取用户信息
//auth.userDetailsService(null);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//所有请求验证接口并关闭CSRF、放行/login 其余全部请求拦截
http.authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and().logout().permitAll() //允许所有用户登出
.and().httpBasic()
.and().csrf().disable();
}
@Autowired
public void setCustomerAuthenticationProvider(CustomerAuthenticationProvider customerAuthenticationProvider) {
this.customerAuthenticationProvider = customerAuthenticationProvider;
}
/**
* 注入AuthenticationManager管理器
**/
@Override
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
会话保存
Spring Security 默认使用Session会话,Session是服务器会话,Session存在跨域请求不是很友好,后续会发布JWT版本。
异常处理
- AuthenticationException 认证失败异常 如密码错误
实现AuthenticationEntryPoint接口,重写commence() 方法
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.getWriter().write("login failed:" + authException.getMessage());
}
}
- AccessDeniedException 访问资源无权异常
实现AccessDeniedHandler接口,重写handle() 方法
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setStatus(403);
response.getWriter().write("Forbidden:" + accessDeniedException.getMessage());
}
}
- Security 配置类
http.authorizeRequests()
...
...
.and()
.exceptionHandling()
.authenticationEntryPoint(myAuthenticationEntryPoint)
.accessDeniedHandler(myAccessDeniedHandler)
.and()
资源鉴权
- 注解方式 @PreAuthorize(“”)+ @EnableGlobalMethodSecurity(prePostEnabled = true) 开启注解方式。
- 动态鉴权
测试


登陆成功后会有session,请求其他接口带上sessionId,访客认证成功

带Session调用Test接口

本文主要介绍了Spring Security在前后端分离环境下的应用,包括认证流程、整体集成项目的配置和资源鉴权处理。讲解了如何自定义认证器、实现UserDetailsService接口、URL拦截以及异常处理,展示了Spring Security的灵活性和可扩展性。
2461

被折叠的 条评论
为什么被折叠?



