Technology Sharing

19.JWT

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1►JWT Blog Recommendation

Teacher Ruan explained it very well. The website is as follows:

http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html

2How does ►ry implement JWT?

Question 1: Is there a token when not logged in?

A: No, so you can only log in on the login page. If you want to jump to other interfaces, you will be redirected to the login page and forced to log in. The front-end blocking code is as follows:

Question 2: When is the token generated?

A: It is generated when logging in. The specific code is as follows:

  1. public String login(String username, String password, String code, String uuid)
  2. {
  3. boolean captchaOnOff = configService.selectCaptchaOnOff();
  4. // 验证码开关
  5. if (captchaOnOff)
  6. {
  7. validateCaptcha(username, code, uuid);
  8. }
  9. // 用户验证
  10. Authentication authentication = null;
  11. try
  12. {
  13. // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
  14. authentication = authenticationManager
  15. .authenticate(new UsernamePasswordAuthenticationToken(username, password));
  16. }
  17. catch (Exception e)
  18. {
  19. if (e instanceof BadCredentialsException)
  20. {
  21. AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
  22. throw new UserPasswordNotMatchException();
  23. }
  24. else
  25. {
  26. AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
  27. throw new ServiceException(e.getMessage());
  28. }
  29. }
  30. AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
  31. LoginUser loginUser = (LoginUser) authentication.getPrincipal();
  32. recordLoginInfo(loginUser.getUserId());
  33. // 生成token
  34. return tokenService.createToken(loginUser);
  35. }