java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot token验证登陆

springboot实现token验证登陆状态的示例代码

作者:温正实

本文主要介绍了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>

到此这篇关于springboot实现token验证登陆状态的示例代码的文章就介绍到这了,更多相关springboot token验证登陆 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文