JWT\
参考文章使用JWT实现单点登录(完全跨域方案)
JWT 分为三个部分
头部携带元数据主体携带用户信息结尾携带校验信息
1.pom
<dependencies>
<dependency>
<groupId>io.jsonwebtoken
</groupId>
<artifactId>jjwt
</artifactId>
</dependency>
</dependencies>
2. java代码
import io
.jsonwebtoken
.Claims
;
import io
.jsonwebtoken
.Jws
;
import io
.jsonwebtoken
.Jwts
;
import io
.jsonwebtoken
.SignatureAlgorithm
;
import org
.springframework
.http
.server
.reactive
.ServerHttpRequest
;
import org
.springframework
.util
.StringUtils
;
import javax
.servlet
.http
.HttpServletRequest
;
import java
.util
.Date
;
public class JwtUtils {
public static final long EXPIRE
= 1000 * 60 * 60 * 24;
public static final String APP_SECRET
= "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
public static String
getJwtToken(String id
, String nickname
){
String JwtToken
= Jwts
.builder()
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg", "HS256")
.setSubject("guli-user")
.setIssuedAt(new Date())
.setExpiration(new Date(System
.currentTimeMillis() + EXPIRE
))
.claim("id", id
)
.claim("nickname", nickname
)
.signWith(SignatureAlgorithm
.HS256
, APP_SECRET
)
.compact();
return JwtToken
;
}
public static boolean checkToken(String jwtToken
) {
if(StringUtils
.isEmpty(jwtToken
)) return false;
try {
Jwts
.parser().setSigningKey(APP_SECRET
).parseClaimsJws(jwtToken
);
} catch (Exception e
) {
e
.printStackTrace();
return false;
}
return true;
}
public static boolean checkToken(HttpServletRequest request
) {
try {
String jwtToken
= request
.getHeader("token");
if(StringUtils
.isEmpty(jwtToken
)) return false;
Jwts
.parser().setSigningKey(APP_SECRET
).parseClaimsJws(jwtToken
);
} catch (Exception e
) {
e
.printStackTrace();
return false;
}
return true;
}
public static String
getMemberIdByJwtToken(HttpServletRequest request
) {
String jwtToken
= request
.getHeader("token");
if(StringUtils
.isEmpty(jwtToken
)) return "";
Jws
<Claims> claimsJws
= Jwts
.parser().setSigningKey(APP_SECRET
).parseClaimsJws(jwtToken
);
Claims claims
= claimsJws
.getBody();
return (String
)claims
.get("id");
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-2766.html