springBoot + Vue + jwt 验证
1 导入依赖:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.1</version>
</dependency>
2 JwtUtil工具类
package com.demo.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.demo.entity.Admin;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
private static final String SECRET = "my_secret";
private static final long EXPIRATION = 1;
public static String createToken(Admin admin) {
Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
System.out.println(expireDate.getTime());
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = JWT.create()
.withHeader(map)
.withClaim("id", admin.getId())
.withClaim("userName", admin.getAdmin())
.withClaim("password", admin.getPassword())
.withExpiresAt(expireDate)
.withIssuedAt(new Date())
.sign(Algorithm.HMAC256(SECRET));
return token;
}
public static boolean verifyToken(String token) {
try{
DecodedJWT jwt=JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
}catch (Exception e){
return false;
}
return true;
}
}
3 Vue index.js 路由
router.beforeEach((to,from,next)=>{
if(to.path.startsWith("/login")){
window.localStorage.getItem("access-admin")
next()
}else{
let admin=JSON.parse(window.localStorage.getItem("access-admin"))
if(!admin){
next({path:"/login"})
}else{
axios.post("http://localhost:8181/demo/parseToken",admin).then(data=> {
console.log(data.data)
if(!data.data){
next({path:"/login"})
localStorage.remover("access-admin")
}
})
}
next()
}
})
export default router;
4 Login.vue
login() {
this.$refs.formLabelAlign.validate((visible) => {
if (visible) {
axios.post("http://localhost:8181/demo/login", this.formLabelAlign).then(data => {
console.log(data.data.token)
if (data.data != null&& data.data!="") {
window.localStorage.setItem("access-admin",JSON.stringify(data.data.token));
this.$message({
message: '登录成功!',
type: 'success'
});
}else{
this.$message({
message: '用户名或密码错误',
type: 'error'
});
}
})
} else {
console.log("error")
return false;
}
})
},
5 Controller 层
@PostMapping("/login")
public Admin getLogin(@RequestBody Admin admin){
Admin ad=indexService.queryAdmin(admin);
if(ad !=null ){
String token =JwtUtil.createToken(admin);
ad.setToken(token);
return ad;
}
return null;
}
@PostMapping("/parseToken")
public boolean parseToken(@RequestBody String token){
return JwtUtil.verifyToken(token);
}