前后端分离中 Spring Security 3.0 的基本使用

环境说明:

  1. JDK:17
  2. Spring Boot: 3.4.0
  3. Spring Security: 6.4

0X00 概要

目标:

  1. 实现一个登录接口且配置该接口不需要认证;
  2. 实现 JWT 的认证;
  3. 自定义认证失败;

0x01 基础配置

密码编码格式的设置

// cn.keeploving.demo.config.SecurityConfig

@Bean
public PasswordEncoder passwordEncoder() {
   
    return new BCryptPasswordEncoder();
}

实现 UserDetailsService,该接口仅有一个方法:loadUserByUsername,是根据登录的凭证(如:用户名、手机号、邮箱等)获取用信息的。

// cn.keeploving.demo.config.SecurityConfig

@Bean
public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
   
    // 这里使用 memory的,也可以自己继承进行实现
    // 这里就意味着有一个账号test,密码是 abc@123
    return new InMemoryUserDetailsManager(
            new User("test",
                    passwordEncoder.encode("abc@123"),
                    new ArrayList<>()
            )
    );
}

0x02 登录接口的实现

基本的登录接口的需要实现一下功能:

  1. 验证登录输入的验证码(如果有);
  2. 检查账号是否存在、密码是否正确,不存在(正确)则返回提示信息,如:用户名或密码错误;
  3. 检查账号的其他状态,返回对应的提示信息,如:账号已经锁定;
  4. 验证成功返回 JWT。

使用 Spring security 认证时需要先注入 AuthenticationManager,代码如下:

// cn.keeploving.demo.config.SecurityConfig

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
   
    return configuration.getAuthenticationManager();
}

然后使用 AuthenticationManager 的 authenticate 方法进行认证是会抛出异常,如下:

  • BadCredentialsException:当登录凭证(如密码)错误时抛出的异常
  • UsernameNotFoundException:未找到账号时抛出异常
  • DisabledException:账号被禁用时抛出的异常
  • LockedException:账号被锁定时抛出的异常

还有更多可能排除的异常,但是这几个异常是和账号信息有关的,它们都是 AccountStatusException 的子类,所以登录时可以捕获它们来返回登录失败信息,具体的代码如下:

// cn.keeploving.demo.controller.AuthController

@RestController
@RequestMapping("auth")
public class AuthController {
   

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public String login(@RequestBody LoginDto loginDto) {
   
        // TODO:验证验证码

        // 登录认证
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
        try {
   
            Authentication authenticate = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            // 生成JWT并返回
            Date now = new Date()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值