JWT javawebtoken 简单案例

终于知道JWT 怎么玩了,直接上代码如下:

package birunet.jwt.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.DecodedJWT;

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

import org.share.domain.tree.dao.SMUser;

public class JwtUtils {

    // 创建token
    public static String creatToken(SMUser user) throws IllegalArgumentException, UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256("secret");
        String username = user.getUserId();
        Map map = new HashMap();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create().withHeader(map).withClaim("username", username)
                .withExpiresAt(new Date(System.currentTimeMillis() + 360000)).sign(algorithm);
        return token;
    }

    // 验证jwt
    public static DecodedJWT verifyJwt(String token) {
        DecodedJWT decodedJWT = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret");
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            decodedJWT = jwtVerifier.verify(token);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        return decodedJWT;
    }
}

初探参考地址
如上代码参考地址

你可能感兴趣的:(Java基础篇)