springboot實(shí)現(xiàn)token驗(yàn)證登陸狀態(tài)的示例代碼
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、寫個(gè)持久工具類
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"; // 用于簽署和驗(yàn)證令牌的密鑰,請(qǐng)?zhí)鎿Q為自己的密鑰
private final Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
private final long validityInMilliseconds = 3600000; // 令牌有效期一小時(shí)
// 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、啟動(dòng)服務(wù)器測(cè)試下,寫個(gè)controller和html,客戶端請(qǐng)求獲取token
controller(生成token 與驗(yàn)證 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) {
// 在實(shí)際應(yīng)用中,你可以驗(yàn)證用戶名和密碼,然后生成令牌
// 這里只是一個(gè)簡(jiǎn)單的示例,假設(shè)用戶名有效
String username = request.getUsername();
String token = jwtUtil.generateToken(username);
return token;
}
// 驗(yàn)證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 (請(qǐng)求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;
// 發(fā)送登錄請(qǐng)求到后端
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>到此這篇關(guān)于springboot實(shí)現(xiàn)token驗(yàn)證登陸狀態(tài)的示例代碼的文章就介紹到這了,更多相關(guān)springboot token驗(yàn)證登陸 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot整合JWT(JSON?Web?Token)生成token與驗(yàn)證的流程及示例
- springboot+shiro+jwtsession和token進(jìn)行身份驗(yàn)證和授權(quán)
- SpringBoot集成JWT實(shí)現(xiàn)Token登錄驗(yàn)證的示例代碼
- SpringBoot登錄驗(yàn)證token攔截器的實(shí)現(xiàn)
- 實(shí)戰(zhàn)SpringBoot集成JWT實(shí)現(xiàn)token驗(yàn)證
- Springboot 如何實(shí)現(xiàn)filter攔截token驗(yàn)證和跨域
- SpringBoot整合JWT框架,解決Token跨域驗(yàn)證問(wèn)題
- SpringBoot集成JWT實(shí)現(xiàn)token驗(yàn)證的流程
- SpringBoot下token短信驗(yàn)證登入登出權(quán)限操作(token存放redis,ali短信接口)
- Spring boot+VUE實(shí)現(xiàn)token驗(yàn)證的示例代碼
相關(guān)文章
在已經(jīng)使用mybatis的項(xiàng)目里引入mybatis-plus,結(jié)果不能共存的解決
這篇文章主要介紹了在已經(jīng)使用mybatis的項(xiàng)目里引入mybatis-plus,結(jié)果不能共存的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
詳解Java集合中的基本數(shù)據(jù)結(jié)構(gòu)
總有小伙伴讓我總結(jié)一下Java集合中的基本數(shù)據(jù)結(jié)構(gòu)的相關(guān)知識(shí),今天特地整理了本篇文章,文中有非常詳細(xì)的介紹,需要的朋友可以參考下2021-06-06
Java?Stream函數(shù)式編程管道流結(jié)果處理
這篇文章主要為大家介紹了Java?Stream函數(shù)式編程管道流結(jié)果處理的示例過(guò)程解析需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
Java語(yǔ)言ReadWriteLock特性實(shí)例測(cè)試
這篇文章主要介紹了Java語(yǔ)言ReadWriteLock特性實(shí)例測(cè)試,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
Java實(shí)現(xiàn)學(xué)生信息管理界面
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)學(xué)生信息管理界面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
Springboot引入攔截器并放行swagger代碼實(shí)例
這篇文章主要介紹了Springboot引入攔截器并放行swagger代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
JavaWeb學(xué)習(xí)筆記之Filter和Listener
這篇文章主要給大家介紹了關(guān)于JavaWeb學(xué)習(xí)筆記之Filter和Listener的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

