Solve the separation of front and back ends, verification code storage) (1)

The following is a simple sample code for reference only. The front-end code realizes the acquisition of login and verification code, and sends the verification code and username and password to the backend when logging in. The back-end code implements the verification of the verification code and username and password. If the verification passes, a Token is generated and returned to the client.

Front-end code (using 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('');
    });
});

Backend code (using 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);
    }
}

Guess you like

Origin blog.csdn.net/weixin_46286150/article/details/129993300