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