Token authentication (JWT) JwtUtil tools (2)

Here a direct write JwtUtil tools, operation and control are omitted interceptor layer operations

public class JwtUtil {
    /**
     * Expiration Time 15 minutes
     */
    private static final long EXPIRE_TIME = 15 * 60 * 1000;
    /**
     * Token private key
     */
    private static final String TOKEN_SECRET="DD5654D654DSD5S1D65S4D65S1D";


    /**
     * Generate signature expire after 15 minutes
     *
     * @Param userName the user name
     * @Param userId User ID
     * @Return encrypted token
     */
    public static String  sign(String userName,String userId){
        try {
            //expire date
            Date date =new Date(System.currentTimeMillis()+EXPIRE_TIME);
            // private key encryption algorithm and
            Algorithm algorithm=Algorithm.HMAC256(TOKEN_SECRET);
            // Set header information
            Map<String,Object> header=new HashMap<>(2);
            header.put("typ","JWT");
            header.put("alg","hs256");
            // userName userId incidental information, generating a signature
            return  JWT.create()
                    .withHeader(header)
                    .withClaim("userName",userName)
                    .withClaim("userId",userId)
                    .withExpiresAt(date)
                    .sign(algorithm);

        }catch (Exception ex){
            return null;
        }
    }

    /**
     * Check whether the correct token
     *
     * @Param token key
     * @Return correct
     */
    public static boolean  verify(String token){
        try{
            Algorithm algorithm=Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier=JWT.require(algorithm)
                    .build();
            DecodedJWT JWT=verifier.verify(token);
            return true;
        }catch (Exception ex){
            return false;
        }
    }

    /**
     * Access to information in the token can get without having secret decryption
     *
     * @Param token key
     * User name @return token included
     */
    public static String  getUserName(String token){
        try {
            DecodedJWT jwt=JWT.decode(token);
            return  jwt.getClaim("userName").asString();
        }catch (JWTDecodeException ex){
            return null;
        }
    }

    /**
     * Access to information in the token can get without having secret decryption
     *
     * @Param token key
     * User ID @return token contained
     */
    public static String  getUserId(String token){
        try {
            DecodedJWT jwt=JWT.decode(token);
            return jwt.getClaim("userId").asString();
        }catch (JWTDecodeException ex){
            return null;
        }
    }
}

  

Guess you like

Origin www.cnblogs.com/BigPig-Winnie/p/11813568.html