当前位置: 首页 > >

Spring Boot½Ì³Ì£ºSpringBootÕûºÏJWT

发布时间:

¼ò½é

Json web token (JWT), ÊÇΪÁËÔÚÍøÂçÓ¦Óû·¾³¼ä´«µÝÉùÃ÷¶øÖ´ÐеÄÒ»ÖÖ»ùÓÚJSONµÄ¿ª·Å±ê×¼£¨(RFC 7519).¸Ãtoken±»Éè¼ÆΪ½ô´ÕÇÒ°²È«µÄ£¬ÌرðÊÊÓÃÓÚ·Ö²¼Ê½Õ¾µãµÄµ¥µãµÇ¼£¨SSO£©³¡¾°¡£JWTµÄÉùÃ÷Ò»°ã±»ÓÃÀ´ÔÚÉí·ÝÌṩÕߺͷþÎñÌṩÕ߼䴫µÝ±»ÈÏÖ¤µÄÓû§Éí·ÝÐÅÏ¢£¬ÒÔ±ãÓÚ´Ó×ÊÔ´·þÎñÆ÷»ñÈ¡×ÊÔ´£¬Ò²¿ÉÒÔÔö¼ÓһЩ¶îÍâµÄÆäËüÒµÎñÂß¼­Ëù±ØÐëµÄÉùÃ÷ÐÅÏ¢£¬¸ÃtokenÒ²¿ÉÖ±½Ó±»ÓÃÓÚÈÏÖ¤£¬Ò²¿É±»¼ÓÃÜ¡£


JWT½á¹¹

JWT µÄÈý¸ö²¿·ÖÒÀ´ÎÈçÏ¡£
Header£¨Í·²¿£©
Payload£¨¸ºÔØ£©
Signature£¨Ç©Ãû£©
1.Header ²¿·ÖÊÇÒ»¸ö JSON ¶ÔÏó£¬ÃèÊö JWT µÄÔªÊý¾Ý£¬Í¨³£ÊÇÏÂÃæµÄÑù×Ó¡£
{
¡°alg¡±: ¡°HS256¡±,
¡°typ¡±: ¡°JWT¡±
}
ÉÏÃæ´úÂëÖУ¬algÊôÐÔ±íʾǩÃûµÄËã·¨£¨algorithm£©£¬Ä¬ÈÏÊÇ HMAC SHA256£¨Ð´³É HS256£©£»typÊôÐÔ±íʾÕâ¸öÁîÅÆ£¨token£©µÄÀàÐÍ£¨type£©£¬JWT ÁîÅÆͳһдΪJWT¡£
2.Payload ²¿·ÖÒ²ÊÇÒ»¸ö JSON ¶ÔÏó£¬ÓÃÀ´´æ·Åʵ¼ÊÐèÒª´«µÝµÄÊý¾Ý¡£JWT ¹æ¶¨ÁË7¸ö¹Ù·½×ֶΣ¬¹©Ñ¡Óá£
iss (issuer)£ºÇ©·¢ÈË
exp (expiration time)£º¹ýÆÚʱ¼ä
sub (subject)£ºÖ÷Ìâ
aud (audience)£ºÊÜÖÚ
nbf (Not Before)£ºÉúЧʱ¼ä
iat (Issued At)£ºÇ©·¢Ê±¼ä
jti (JWT ID)£º±àºÅ
×¢Ò⣬JWT ĬÈÏÊDz»¼ÓÃܵģ¬ÈκÎÈ˶¼¿ÉÒÔ¶Áµ½£¬ËùÒÔ²»Òª°ÑÃØÃÜÐÅÏ¢·ÅÔÚÕâ¸ö²¿·Ö¡£Õâ¸ö JSON ¶ÔÏóҲҪʹÓà Base64URL Ë㷨ת³É×Ö·û´®¡£
3.Signature ²¿·ÖÊǶÔÇ°Á½²¿·ÖµÄÇ©Ãû£¬·ÀÖ¹Êý¾Ý´Û¸Ä¡£
Ê×ÏÈ£¬ÐèÒªÖ¸¶¨Ò»¸öÃÜÔ¿£¨secret£©¡£Õâ¸öÃÜÔ¿Ö»ÓзþÎñÆ÷²ÅÖªµÀ£¬²»ÄÜй¶¸øÓû§¡£È»ºó£¬Ê¹Óà Header ÀïÃæÖ¸¶¨µÄÇ©ÃûËã·¨£¨Ä¬ÈÏÊÇ HMAC SHA256£©£¬°´ÕÕÏÂÃæµÄ¹«Ê½²úÉúÇ©Ãû¡£


Éú²útokenºÍÑéÖ¤tokenµÄ²âÊÔdemo

@Test
void contextLoads() {
//Éú²útoken
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,1000);

String token = JWT.create()
//ÉèÖÃÔØÌå
.withClaim("username","zhangsan")
.withClaim("userid",12)
//token¹ýÆÚʱ¼ä
.withExpiresAt(instance.getTime())
//Ç©Ãû
.sign(Algorithm.HMAC256("123456"));
System.out.println(token);
}

@Test
void contextLoads2() {
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123456")).build();
//ÑéÖ¤token
DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDM2Mjk3NDYsInVzZXJpZCI6MTIsInVzZXJuYW1lIjoiemhhbmdzYW4ifQ.G8LCea3egNGrBLNr996iX6-ir0i7dqJkFWJaqGKclGI
");
//ÑéÖ¤³É¹¦ºóÈ¡³öÔØÌå
System.out.println(verify.getClaims().get("username").toString());
System.out.println(verify.getClaims().get("userid").asInt());
}

ÕûºÏspringbootµÇ¼¹¦ÄÜdemo

ÒýÈëÒÀÀµ



com.auth0
java-jwt
3.4.0


ÅäÖÃymlÎļþ£¨ÕâÀï²»²éÊý¾Ý¿â£¬Ö±½ÓÔÚÕâÀﶨÒåÓû§ÕýÈ·µÄµÇ¼ÃûºÍÃÜÂ룩


server:
port: 8888

Login:
username: zhangsan
password: 123456

´´½¨ÊµÌå


@Data
public class User {

private Integer id;

private String password;

private String username;
}

´´½¨JWTutils


public class JWTUtils {

//»ñÈ¡token
public static String getToken(User u){
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE,7); //ĬÈÏÁîÅƹýÆÚʱ¼ä7Ìì

JWTCreator.Builder builder = JWT.create();
builder.withClaim("userId",u.getId())
.withClaim("username",u.getUsername());

String token = builder.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256(u.getPassword()));
return token;
}

//ÑéÖ¤tokenºÏ·¨ÐÔ ³É¹¦·µ»Øtoken
public static DecodedJWT verify(String token){
//»ñÈ¡µÇ¼Óû§ÕæÕýµÄÃÜÂë¼ÙÈçÊý¾Ý¿â²é³öÀ´µÄÊÇ123456
String password = ¡°123456¡±;
JWTVerifier build = JWT.require(Algorithm.HMAC256(password)).build();
DecodedJWT verify = build.verify(token);
return verify;
}
}

´´½¨jwtÀ¹½*÷


public class JWTInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
try {
JWTUtils.verify(token);
}catch (SignatureVerificationException e){
e.printStackTrace();
System.out.println("ÎÞЧǩÃû");
return false;
}catch (TokenExpiredException e){
e.printStackTrace();
System.out.println("token¹ýÆÚ");
return false;
}catch (AlgorithmMismatchException e){
e.printStackTrace();
System.out.println("tokenËã·¨²»Ò»ÖÂ");
return false;
}catch (Exception e){
e.printStackTrace();
System.out.println("tokenÎÞЧ");
return false;
}
return true;
}
}

½«À¹½*÷×¢Èëµ½MVC


@Configuration
public class IntercaptorConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
//À¹½ØµÄ·¾¶
.addPathPatterns("/**")
//ÅųýµÇ¼½Ó¿Ú
.excludePathPatterns("/user/login");
}
}

contoller²âÊÔ


@RestController
public class UserLoginContoller {

@Value("${Login.username}")
private String realUsername;

@Value("${Login.password}")
private String realPassword;

@GetMapping("user/login")
public String login(String username,String password){
if(username.equals(realUsername) && password.equals(realPassword)){
User u = new User();
u.setPassword(password);
u.setUsername(username);
String token = JWTUtils.getToken(u);
return token;
}
return "µÇ¼ʧ°Ü£¡Õ˺ŻòÕßÃÜÂë²»¶Ô£¡";
}

@GetMapping("user/test")
public String testLogin(){
return "µÇ¼³É¹¦ºó£¬²Å¿ÉÒÔ·ÃÎÊ£¡";
}
}

ÏȵǼlogin³É¹¦Ö®ºó»á·µ»Øtoken£¬È»ºóÓÃpostman Header´ø×Åtoken·ÃÎÊuser/testÑéÖ¤



友情链接: 简历 面试求职范文 职业规划 自我管理 社交礼仪 76242百科