自学内容网 自学内容网

spring boot 实现token验证登陆状态

1、添加maven依赖到pom.xml

<dependency>
                    <groupId>io.jsonwebtoken</groupId>
                   <artifactId>jjwt-api</artifactId>
                   <version>0.11.5</version>
               </dependency>
               <dependency>
                   <groupId>io.jsonwebtoken</groupId>
                    <artifactId>jjwt-impl</artifactId>
                  <version>0.11.5</version>
              </dependency>


               <dependency>
                    <groupId>io.jsonwebtoken</groupId>
                    <artifactId>jjwt-gson</artifactId>
                    <version>0.11.5</version>
               </dependency>

2、写个持久工具类

package com.scxhgh.scxhgh.token_session;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

@Component
public class JwtUtil {


//
//      <dependency>
//            <groupId>io.jsonwebtoken</groupId>
//            <artifactId>jjwt-api</artifactId>
//            <version>0.11.5</version>
//        </dependency>
//        <dependency>
//            <groupId>io.jsonwebtoken</groupId>
//            <artifactId>jjwt-impl</artifactId>
//            <version>0.11.5</version>
//        </dependency>
//
//
//        <dependency>
//            <groupId>io.jsonwebtoken</groupId>
//            <artifactId>jjwt-gson</artifactId>
//            <version>0.11.5</version>
//        </dependency>


    private final String secretKey = "dshhdshissajsakpxfksxxz"; // 用于签署和验证令牌的密钥,请替换为自己的密钥
    private final Key key = Keys.hmacShaKeyFor(secretKey.getBytes());

    private final long validityInMilliseconds = 3600000; // 令牌有效期一小时
//    private final long validityInMilliseconds = 60000; // 令牌有效期一分钟
    public String generateToken(String username) {
        Date now = new Date();
        Date validity = new Date(now.getTime() + validityInMilliseconds);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(validity)
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    public boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

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

    controller(生成token 与验证 token):

package com.scxhgh.scxhgh.token_session;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserController {


    private final JwtUtil jwtUtil;

    public UserController(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

//    生成token
    @PostMapping("/login_token")
    public String login(@RequestBody UserLoginRequest request) {
        // 在实际应用中,你可以验证用户名和密码,然后生成令牌
        // 这里只是一个简单的示例,假设用户名有效

        String username = request.getUsername();
        String token = jwtUtil.generateToken(username);

        return token;
    }
    
//    验证token
    
    

    @GetMapping("/user")
    public String getUserInfo(@RequestHeader("Authorization") String token) {
        if (jwtUtil.validateToken(token)) {
            String username = jwtUtil.getUsernameFromToken(token);
            return "Hello, " + username + "!";
        } else {
            return "Invalid token";
        }
    }
}

html (请求token)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form id="login-form">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required><br><br>

  <label for="password">Password:</label>
  <input type="password" id="password" name="password" required><br><br>

  <button type="button" onclick="login()">Login</button>
</form>

<div id="token-info" style="display: none;">
  <h2>Token Information</h2>
  <p id="token-content"></p>
</div>

<script>
  function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    // 发送登录请求到后端
    fetch('/api/login_token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ username, password })
    })
            .then(response => response.text())
            .then(token => {
              // 显示令牌信息
              document.getElementById('token-info').style.display = 'block';
              document.getElementById('token-content').textContent = 'Token: ' + token;
            })
            .catch(error => {
              console.error('Login failed:', error);
            });
  }
</script>
</body>
</html>


原文地址:https://blog.csdn.net/WenZhengshi/article/details/140530910

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!