欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > spring boot 实现token验证登陆状态

spring boot 实现token验证登陆状态

2024/10/23 19:18:17 来源:https://blog.csdn.net/WenZhengshi/article/details/140530910  浏览:    关键词: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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com