JWT的简单实现(简单示例)

2018-08-23更新:

了解到新的jwt生成和解析方式。

pom.xml


	io.jsonwebtoken
	jjwt
	0.7.0

生成解析方法:

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * Created by 孙乐进 on 2018/8/9.
 */
@RestController
@RequestMapping("/api")
public class JwtUtil {

    private static final String JWTSECRET = "myScrect";
    /**
     * 生成jwt
     * @param userId
     * @return
     */
    @GetMapping("/jwt/create/{userId}")
    public static String createToken(@PathVariable  String userId) {
        String token = Jwts.builder()
                .setSubject(userId)
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000 * 365))
                .signWith(SignatureAlgorithm.HS512, JWTSECRET)
                .compact();
        return token;
    }

    //解析jwt
    @GetMapping("/jwt/verify/{token}")
    public static String verifyToken(@PathVariable String token){
        String user = Jwts.parser()
                .setSigningKey(JWTSECRET)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
        return user;
    }

}

最近在学习使用springcloud的时候碰到session不好跨服务器(redis可实现),所以想着整合springSecurity+springboot+jwt,实现无状态身份认证。

------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 

pom.xml


    com.auth0
    java-jwt
    3.1.0

 

JWT生成:

    private static String SECRET = "mysecret";

    @GetMapping("/jwt/create/{info}")
    public static String createToken(@PathVariable String info) throws UnsupportedEncodingException {
        Date iatDate = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,100);
        Date expiresDate = nowTime.getTime();

        Map map = new HashMap();
        map.put("alg","HS256");
        map.put("type","JWT");
        String token = JWT.create().withHeader(map)
                .withClaim("info",info)
                .withExpiresAt(expiresDate)
                .withIssuedAt(iatDate)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

 

JWT解析:

    @GetMapping("/jwt/analyze/{token}")
    public static String verifyToken(@PathVariable String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        jwt = verifier.verify(token);
        Map result = jwt.getClaims();

        jwt.getKeyId() ;
        jwt.getToken();
        jwt.getClaim("info").asString();

        return result.get("info").asString();
    }

 

你可能感兴趣的:(Java)