Spring Security重写AuthenticationManager实现账号密码登录或者手机号码登录
作者:餘yuqn
使用 Spring Security 重写AuthenticationManager实现账号密码登录或者手机号码登录,Spring Security默认使用账号密码进行登录,通过将账号密码写入到UsernamePasswordAuthenticationToken中,认证成功后创建一个包含用户信息和权限的认证令牌;在UsernamePasswordAuthenticationToken认证的时候,调用UserDetailsService进行校验(此次可以自己写逻辑进行校验,如查数据库),并且返回UserDetails(用户信息类)。
在此基础上实现功能:用户能够使用账号+密码登录;用户能够使用手机号码登录(个人暂时只需要用到手机号码+第三方验证码登录,可以根据需求更改配置)。
一、创建自定义认证提供者CustomAuthenticationProvider
import com.yuqn.service.impl.PhoneNumberUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
public class CustomAuthenticationProvider implements AuthenticationProvider {
private UserDetailsService userDetailsService;
private PasswordEncoder passwordEncoder;
private PhoneNumberUserService phoneNumberUserService;
public CustomAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder, PhoneNumberUserService phoneNumberUserService) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
this.phoneNumberUserService = phoneNumberUserService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 接收认证信息
String credentials = (String) authentication.getCredentials();
String principal = (String) authentication.getPrincipal();
// 判断是账号登录还是手机号登录,这里简单通过前缀区分
UserDetails userDetails = null;
if (principal.startsWith("username:")) {
// 账号登录
String username = principal.substring("username:".length());
userDetails = userDetailsService.loadUserByUsername(username);
if (!passwordEncoder.matches(credentials, userDetails.getPassword())) {
throw new BadCredentialsException("Invalid username or password");
}
} else if (principal.startsWith("phone:")) {
// 手机号登录
// 这里需要有一个根据手机号加载用户信息的方法,比如 userDetailsService.loadUserByPhoneNumber(phoneNumber)
// 但由于UserDetailsService没有提供这样的方法,所以这里只是一个示例,你需要自己实现这个逻辑
String phoneNumber = principal.substring("phone:".length());
// 手机号码登录
userDetails = phoneNumberUserService.loadUserByPhoneNumber(phoneNumber);
} else {
throw new BadCredentialsException("Invalid principal format");
}
// 如果用户信息验证成功,则创建一个新的已认证令牌并返回
UsernamePasswordAuthenticationToken authenticatedToken = new UsernamePasswordAuthenticationToken(userDetails, credentials, userDetails.getAuthorities());
authenticatedToken.setDetails(authentication.getDetails());
return authenticatedToken;
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
二、创建认证业务UserDetailsService、PhoneNumberUserService
创建两个验证类,用于进行用户认证,其中UserDetailsService认证账号密码登录,PhoneNumberUserService认证手机号码登录(我这里手机号码唯一,通过手机号码查询用户,具体逻辑根据自己业务来)
UserDetailsService类:
/**
* @author: yuqn
* @Date: 2024/5/21 23:34
* @description:
* secutiry类
* 重写登录验证方法,常规方法是 loadUserByUsername 接收传递的参数,进行security自定义的校验
* 这里重写 loadUserByUsername 方法,自定义校验方法(如查询数据库是否存在此人)
* @version: 1.0
*/
@Service
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
@Autowired
private UserMapper userMapper;
@Autowired
private MenuMapper menuMapper;
/**
* @author: yuqn
* @Date: 2024/11/24 0:30
* @description:
* 根据用户名查询到用户信息,并且映射到UserDetails
* @param: null
* @return: null
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 查询用户
System.out.println("username==" + username);
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUserName,username);
User user = userMapper.selectOne(queryWrapper);
System.out.println("user = " + user);
// 如果没有用户就抛出异常
if(Objects.isNull(user)){
throw new RuntimeException("用户名或者密码错误");
}
// 查询对应权限
// List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
List<String> list = menuMapper.selectPermsByUserId(user.getId());
list.add(user.getRoles());
System.out.println("list = " + list);
// 将user封装到 LoginUser 返回,security 会根据 LoginUser 获取账号密码进行校验,数据库中的密码需要使用{noop}表示明文保存的,不然会报错,因为security使用的加密校验
return new LoginUser(user,list);
}
}
PhoneNumberUserService类:
/**
* @author: yuqn
* @Date: 2024/11/26 11:09
* @description:
* 电话号码查询用户,封装到UserDetails,用于CustomAuthenticationProvider验证
* @version: 1.0
*/
@Service
public class PhoneNumberUserService {
@Autowired
private UserMapper userMapper;
@Autowired
private MenuMapper menuMapper;
/**
* @author: yuqn
* @Date: 2024/11/26 11:04
* @description:
* 自定义手机号码验证
* @param: null
* @return: null
*/
public UserDetails loadUserByPhoneNumber(String phoneNumber){
// 根据手机号码查询用户
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getPhonenumber,phoneNumber);
User user = userMapper.selectOne(queryWrapper);
// 如果没有用户就抛出异常
if(Objects.isNull(user)){
throw new RuntimeException("用户名或者密码错误");
}
// 查询对应权限
// List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
List<String> list = menuMapper.selectPermsByUserId(user.getId());
list.add(user.getRoles());
System.out.println("list = " + list);
// 将user封装到 LoginUser 返回,security 会根据 LoginUser 获取账号密码进行校验,数据库中的密码需要使用{noop}表示明文保存的,不然会报错,因为security使用的加密校验
return new LoginUser(user,list);
}
}
三、更改配置类
注入自定义认证提供者CustomAuthenticationProvider,从而实现逻辑。
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService userDetailsService() {
// 返回你的UserDetailsService实现
return new UserDetailsService();
}
@Bean
public PhoneNumberUserService phoneNumberUserService(){
return new PhoneNumberUserService();
}
@Bean
public CustomAuthenticationProvider customAuthenticationProvider() {
return new CustomAuthenticationProvider(userDetailsService(), passwordEncoder(),phoneNumberUserService());
}
四、登录业务类
登录接口调用该业务类,将用户信息存入到UsernamePasswordAuthenticationToken实现自定义认证,认证成功后生成一个凭证,用户返回给调用者。
@Override
public Result login(User user) {
//authenticationManager authenticate 进行用户认证,通过封装的authenticationToken进行验证
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
System.out.println("authenticationToken = " + authenticationToken);
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
System.out.println("authenticate = " + authenticate);
// 如果认证没提过,给出对应的提示
if(Objects.isNull(authenticate)){
throw new RuntimeException("登录失败");
}
//如果认证通过,使用userid生成一个jwt,jwt存入responseresult返回
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
System.out.println("loginuser:" + loginUser);
String userid = loginUser.getUser().getId().toString();
String jwt = JwtUtil.createJWT(userid);
Map<String,String> map = new HashMap<>();
map.put("token",jwt);
//把完整的用户信息存入到redis userid作为key
redisCache.setCacheObject("login:" + userid, loginUser);
return Result.OK("登录成功",map);
}
五、写接口
@PostMapping("/user/login")
public Result login(@RequestBody User user){
// 登录
return loginService.login(user);
}
六、测试


七、总结
UsernamePasswordAuthenticationToken提供的方法参数是用户名、用户名+密码、用户名+密码+权限,所以使用手机号码登录,实际上是将手机号码当成用户名,通过自定义认证器进行拦截并处理,最终实现效果。
到此这篇关于Spring Security重写AuthenticationManager实现账号密码登录或者手机号码登录的文章就介绍到这了,更多相关SpringSecurity AuthenticationManager登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
