当前位置:   article > 正文

spring boot 实现token验证登陆状态

spring boot 实现token验证登陆状态

1、添加maven依赖到pom.xml

  1. <dependency>
  2. <groupId>io.jsonwebtoken</groupId>
  3. <artifactId>jjwt-api</artifactId>
  4. <version>0.11.5</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.jsonwebtoken</groupId>
  8. <artifactId>jjwt-impl</artifactId>
  9. <version>0.11.5</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>io.jsonwebtoken</groupId>
  13. <artifactId>jjwt-gson</artifactId>
  14. <version>0.11.5</version>
  15. </dependency>

2、写个持久工具类

  1. package com.scxhgh.scxhgh.token_session;
  2. import io.jsonwebtoken.Claims;
  3. import io.jsonwebtoken.Jwts;
  4. import io.jsonwebtoken.SignatureAlgorithm;
  5. import io.jsonwebtoken.security.Keys;
  6. import org.springframework.stereotype.Component;
  7. import java.security.Key;
  8. import java.util.Date;
  9. @Component
  10. public class JwtUtil {
  11. //
  12. // <dependency>
  13. // <groupId>io.jsonwebtoken</groupId>
  14. // <artifactId>jjwt-api</artifactId>
  15. // <version>0.11.5</version>
  16. // </dependency>
  17. // <dependency>
  18. // <groupId>io.jsonwebtoken</groupId>
  19. // <artifactId>jjwt-impl</artifactId>
  20. // <version>0.11.5</version>
  21. // </dependency>
  22. //
  23. //
  24. // <dependency>
  25. // <groupId>io.jsonwebtoken</groupId>
  26. // <artifactId>jjwt-gson</artifactId>
  27. // <version>0.11.5</version>
  28. // </dependency>
  29. private final String secretKey = "dshhdshissajsakpxfksxxz"; // 用于签署和验证令牌的密钥,请替换为自己的密钥
  30. private final Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
  31. private final long validityInMilliseconds = 3600000; // 令牌有效期一小时
  32. // private final long validityInMilliseconds = 60000; // 令牌有效期一分钟
  33. public String generateToken(String username) {
  34. Date now = new Date();
  35. Date validity = new Date(now.getTime() + validityInMilliseconds);
  36. return Jwts.builder()
  37. .setSubject(username)
  38. .setIssuedAt(now)
  39. .setExpiration(validity)
  40. .signWith(key, SignatureAlgorithm.HS256)
  41. .compact();
  42. }
  43. public String getUsernameFromToken(String token) {
  44. Claims claims = Jwts.parserBuilder()
  45. .setSigningKey(key)
  46. .build()
  47. .parseClaimsJws(token)
  48. .getBody();
  49. return claims.getSubject();
  50. }
  51. public boolean validateToken(String token) {
  52. try {
  53. Jwts.parserBuilder()
  54. .setSigningKey(key)
  55. .build()
  56. .parseClaimsJws(token);
  57. return true;
  58. } catch (Exception e) {
  59. return false;
  60. }
  61. }
  62. }

3、启动服务器测试下,写个controller和html,客户端请求获取token

    controller(生成token 与验证 token):

  1. package com.scxhgh.scxhgh.token_session;
  2. import org.springframework.web.bind.annotation.*;
  3. @RestController
  4. @RequestMapping("/api")
  5. public class UserController {
  6. private final JwtUtil jwtUtil;
  7. public UserController(JwtUtil jwtUtil) {
  8. this.jwtUtil = jwtUtil;
  9. }
  10. // 生成token
  11. @PostMapping("/login_token")
  12. public String login(@RequestBody UserLoginRequest request) {
  13. // 在实际应用中,你可以验证用户名和密码,然后生成令牌
  14. // 这里只是一个简单的示例,假设用户名有效
  15. String username = request.getUsername();
  16. String token = jwtUtil.generateToken(username);
  17. return token;
  18. }
  19. // 验证token
  20. @GetMapping("/user")
  21. public String getUserInfo(@RequestHeader("Authorization") String token) {
  22. if (jwtUtil.validateToken(token)) {
  23. String username = jwtUtil.getUsernameFromToken(token);
  24. return "Hello, " + username + "!";
  25. } else {
  26. return "Invalid token";
  27. }
  28. }
  29. }

html (请求token)

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Login Page</title>
  6. </head>
  7. <body>
  8. <h1>Login Page</h1>
  9. <form id="login-form">
  10. <label for="username">Username:</label>
  11. <input type="text" id="username" name="username" required><br><br>
  12. <label for="password">Password:</label>
  13. <input type="password" id="password" name="password" required><br><br>
  14. <button type="button" onclick="login()">Login</button>
  15. </form>
  16. <div id="token-info" style="display: none;">
  17. <h2>Token Information</h2>
  18. <p id="token-content"></p>
  19. </div>
  20. <script>
  21. function login() {
  22. const username = document.getElementById('username').value;
  23. const password = document.getElementById('password').value;
  24. // 发送登录请求到后端
  25. fetch('/api/login_token', {
  26. method: 'POST',
  27. headers: {
  28. 'Content-Type': 'application/json'
  29. },
  30. body: JSON.stringify({ username, password })
  31. })
  32. .then(response => response.text())
  33. .then(token => {
  34. // 显示令牌信息
  35. document.getElementById('token-info').style.display = 'block';
  36. document.getElementById('token-content').textContent = 'Token: ' + token;
  37. })
  38. .catch(error => {
  39. console.error('Login failed:', error);
  40. });
  41. }
  42. </script>
  43. </body>
  44. </html>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/850699
推荐阅读
相关标签
  

闽ICP备14008679号