解决前后端分离,验证码存储)(1)

以下是一个简单的示例代码,仅供参考。前端代码实现了登录和验证码的获取,并在登录时将验证码和用户名密码一起发送到后端。后端代码实现了验证码和用户名密码的验证,如果验证通过则生成Token并返回给客户端。

前端代码(使用jQuery):

// 获取验证码
$('#btn-get-captcha').click(function() {
    
    
    $.get('/captcha', function(data) {
    
    
        $('#captcha-img').attr('src', data.img); // 显示验证码图片
        $('#captcha-key').val(data.key); // 保存验证码key
    });
});

// 登录
$('#btn-login').click(function() {
    
    
    var data = {
    
    
        username: $('#username').val(),
        password: $('#password').val(),
        captchaKey: $('#captcha-key').val(),
        captchaCode: $('#captcha-code').val()
    };
    $.post('/login', data, function(data, textStatus, xhr) {
    
    
        // 登录成功,保存Token并跳转到主页
        var token = xhr.getResponseHeader('Authorization');
        localStorage.setItem('token', token);
        window.location.href = '/index.html';
    }).fail(function() {
    
    
        // 登录失败,刷新验证码
        $('#captcha-img').attr('src', '/captcha?' + Math.random());
        $('#captcha-code').val('');
    });
});

后端代码(使用Spring Boot):

@RestController
public class AuthController {
    
    

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenProvider tokenProvider;

    // 获取验证码
    @GetMapping("/captcha")
    public CaptchaInfo getCaptcha() {
    
    
        // 生成验证码图片和对应的key,保存到redis中
        String key = UUID.randomUUID().toString();
        String code = CaptchaUtil.generateCode();
        BufferedImage image = CaptchaUtil.generateImage(code);
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

        // 返回验证码图片和key
        String img = "data:image/png;base64," + ImageUtil.toBase64(image);
        return new CaptchaInfo(key, img);
    }

    // 登录
    @PostMapping("/login")
    public ResponseEntity<AuthInfo> login(@RequestBody LoginRequest loginRequest) {
    
    
        // 验证用户输入的验证码是否正确
        String key = loginRequest.getCaptchaKey();
        String code = redisTemplate.opsForValue().get(key);
        if (code == null || !code.equalsIgnoreCase(loginRequest.getCaptchaCode())) {
    
    
            throw new BadCredentialsException("Invalid captcha code");
        }

        // 验证用户名密码是否正确
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginRequest.getUsername(), loginRequest.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        // 生成Token
        String token = tokenProvider.createToken(authentication);

        // 返回Token
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
        return new ResponseEntity<>(new AuthInfo(token), headers, HttpStatus.OK);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_46286150/article/details/129993300
今日推荐