com.auth0.jwt.JWTVerifier Java Examples

The following examples show how to use com.auth0.jwt.JWTVerifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JWTAuthenticationFilter.java    From waltz with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Request request, Response response) throws Exception {
    String authorizationHeader = request.headers("Authorization");

    if (authorizationHeader == null) {
        AuthenticationUtilities.setUserAsAnonymous(request);
    } else {
        String token = authorizationHeader.replaceFirst("Bearer ", "");
        DecodedJWT decodedToken = JWT.decode(token);

        JWTVerifier verifier = selectVerifier(decodedToken);

        DecodedJWT decodedJWT = verifier.verify(token);
        AuthenticationUtilities.setUser(request, decodedJWT.getSubject());
    }
}
 
Example #2
Source File: JWTTokenAsUserUniqueIdentifierSsoService.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public String readUserIdentifier(HttpServletRequest request) {
	try {
		String jwtToken = request.getParameter(SsoServiceInterface.USER_ID);
		if (jwtToken == null) {
			logger.debug("JWT token not found in request");
			return null;
		}
		logger.debug("JWT token retrieved : [" + jwtToken + "]");
		JWTVerifier verifier = JWT.require(algorithm).build();
		verifier.verify(jwtToken);
		logger.debug("JWT token verified properly");
		return jwtToken; // we consider the JWT token as user unique identifier
	} catch (JWTVerificationException e) {
		throw new SpagoBIRuntimeException("Invalid JWT token!", e);
	}
}
 
Example #3
Source File: JwtTokenUtils.java    From gpmall with Apache License 2.0 6 votes vote down vote up
/**
 * 解密jwt并验证是否正确
 */
public String freeJwt () {
    DecodedJWT decodedJWT = null;
    try {
        //使用hmac256加密算法
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
                .withIssuer("wlgzs")
                .build();
        decodedJWT = verifier.verify(token);
        log.info("签名人:" + decodedJWT.getIssuer() + " 加密方式:" + decodedJWT.getAlgorithm() + " 携带信息:" + decodedJWT.getClaim("user").asString());
    } catch (Exception e) {
        log.info("jwt解密出现错误,jwt或私钥或签证人不正确");
        throw new ValidateException(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode(),SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
    }
    //获得token的头部,载荷和签名,只对比头部和载荷
    String [] headPayload = token.split("\\.");
    //获得jwt解密后头部
    String header = decodedJWT.getHeader();
    //获得jwt解密后载荷
    String payload = decodedJWT.getPayload();
    if(!header.equals(headPayload[0]) && !payload.equals(headPayload[1])){
        throw new ValidateException(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode(),SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
    }
    return new AESUtil(decodedJWT.getClaim("user").asString()).decrypt();
}
 
Example #4
Source File: JwtUtil.java    From spring-boot-plus with Apache License 2.0 6 votes vote down vote up
public static boolean verifyToken(String token, String salt) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(salt);
        JWTVerifier verifier = JWT.require(algorithm)
                // 签发人
                .withIssuer(jwtProperties.getIssuer())
                // 主题
                .withSubject(jwtProperties.getSubject())
                // 签发的目标
                .withAudience(jwtProperties.getAudience())
                .build();
        DecodedJWT jwt = verifier.verify(token);
        if (jwt != null) {
            return true;
        }
    } catch (Exception e) {
        log.error("Verify Token Exception", e);
    }
    return false;
}
 
Example #5
Source File: JwtApplication.java    From spring-boot-study with MIT License 6 votes vote down vote up
/**
 * 验证 token
 * */
private static void verifyJWTToken(String token) throws JWTVerificationException {
    Algorithm algorithm=Algorithm.HMAC256("secret");
    JWTVerifier verifier = JWT.require(algorithm)
            .withIssuer("SERVICE")
            .build();

    DecodedJWT jwt =verifier.verify(token);
    String subject=jwt.getSubject();
    Map<String,Claim> claims=jwt.getClaims();
    Claim claim = claims.get("loginName");
    System.out.println("自定义 claim:"+claim.asString());

    List<String> audience = jwt.getAudience();
    System.out.println("subject 值:"+subject);
    System.out.println("audience 值:"+audience.get(0));
}
 
Example #6
Source File: AuthenticationFactory.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 删除Token
 *
 * @param token
 * @return
 * @throws Exception
 */
public static void deleteToken(String token) throws Exception {
    String jwtSecret = MappingCache.getValue(MappingConstant.KEY_JWT_SECRET);
    if (StringUtil.isNullOrNone(jwtSecret)) {
        jwtSecret = CommonConstant.DEFAULT_JWT_SECRET;
    }
    Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer("java110").build();
    DecodedJWT jwt = verifier.verify(token);
    String jdi = jwt.getId();
    //保存token Id
    String userId = JWTCache.getValue(jdi);
    if (!StringUtil.isNullOrNone(userId)) { //说明redis中jdi 已经失效
        JWTCache.removeValue(jdi);
    }
}
 
Example #7
Source File: AuthUtils.java    From mdw with Apache License 2.0 6 votes vote down vote up
private static void verifyMdwJWT(String token, Map<String,String> headers) throws Exception {
    // If first call, generate verifier
    JWTVerifier tempVerifier = verifier;
    if (tempVerifier == null)
        tempVerifier = createMdwTokenVerifier();

    if (tempVerifier == null)
        throw new Exception("Cannot generate MDW JWT verifier");

    DecodedJWT jwt = tempVerifier.verify(token);  // Verifies JWT is valid

    // Verify token is not too old, if application specifies property for max token age - in seconds
    if (maxAge > 0 && jwt.getIssuedAt() != null) {
        if ((new Date().getTime() - jwt.getIssuedAt().getTime()) > maxAge)
            throw new Exception("JWT token has expired");
    }

    // Get the user JWT was created for
    if (!StringUtils.isBlank(jwt.getSubject()))
        headers.put(Listener.AUTHENTICATED_USER_HEADER, jwt.getSubject());
    else
        throw new Exception("Received valid JWT token, but cannot identify the user");
}
 
Example #8
Source File: JwtUtils.java    From Ffast-Java with MIT License 6 votes vote down vote up
/**
 * get the object of jwt if not expired
 *
 * @param jwt
 * @return POJO object
 */
public static <T> T unsign(String jwt, Class<T> classT, String secret) {
    final JWTVerifier verifier = new JWTVerifier(SECRET_PREIFX + secret);
    try {
        final Map<String, Object> claims = verifier.verify(jwt);
        if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
            long exp = (Long) claims.get(EXP);
            long currentTimeMillis = System.currentTimeMillis();
            if (exp > currentTimeMillis) {
                String json = (String) claims.get(PAYLOAD);
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.readValue(json, classT);
            }
        }
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage());
        return null;
    }
}
 
Example #9
Source File: AuthUtils.java    From mdw with Apache License 2.0 6 votes vote down vote up
private static synchronized JWTVerifier createMdwTokenVerifier() {
    JWTVerifier tempVerifier = verifier;
    if (tempVerifier == null) {
        String appToken = System.getenv(MDW_APP_TOKEN);
        if (StringUtils.isBlank(appToken))
            logger.error("Exception processing incoming message using MDW Auth token - Missing System environment variable " + MDW_APP_TOKEN);
        else {
            try {
                maxAge = PropertyManager.getIntegerProperty(PropertyNames.MDW_AUTH_TOKEN_MAX_AGE, 0) * 1000L;  // MDW default is token never expires
                Algorithm algorithm = Algorithm.HMAC256(appToken);
                verifier = tempVerifier = JWT.require(algorithm)
                        .withIssuer(MDW_AUTH)
                        .withAudience(ApplicationContext.getAppId())
                        .build(); //Reusable verifier instance
            }
            catch (IllegalArgumentException | UnsupportedEncodingException e) {
                logger.error("Exception processing incoming message using MDW Auth token", e);
            }
        }
    }
    return tempVerifier;
}
 
Example #10
Source File: GRPCAuthConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
private JWTVerifier createVerifier() {
    switch (properties.getAlg()) {
        case HMAC512:
            return JWT
                    .require(Algorithm.HMAC512(properties.getSecret()))
                    .acceptLeeway(2)
                    .build();
        case RSA512:
            return JWT
                    .require(Algorithm.RSA512(new StaticRSAKeyProvider(properties.getKeys())))
                    .acceptLeeway(2)
                    .build();
        default:
            throw new IllegalStateException("Unsupported algorithm");
    }
}
 
Example #11
Source File: OAuth2AuthenticationResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
    Token responseToken = response.readEntity(Token.class);
    assertEquals("BEARER", responseToken.getTokenType().name());

    String token = responseToken.getToken();

    Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
    JWTVerifier jwtVerifier = JWT.require(algorithm).build();

    DecodedJWT jwt = jwtVerifier.verify(token);

    assertEquals(jwt.getSubject(),"[email protected]");

    assertEquals("Jane", jwt.getClaim("firstname").asString());
    assertEquals("gravitee-management-auth", jwt.getClaim("iss").asString());
    assertEquals("[email protected]", jwt.getClaim("sub").asString());
    assertEquals("[email protected]", jwt.getClaim("email").asString());
    assertEquals("Doe", jwt.getClaim("lastname").asString());
}
 
Example #12
Source File: Sign.java    From staffjoy with MIT License 6 votes vote down vote up
static DecodedJWT verifyToken(String tokenString, String signingToken) {
    JWTVerifier verifier = verifierMap.get(signingToken);
    if (verifier == null) {
        synchronized (verifierMap) {
            verifier = verifierMap.get(signingToken);
            if (verifier == null) {
                Algorithm algorithm = Algorithm.HMAC512(signingToken);
                verifier = JWT.require(algorithm).build();
                verifierMap.put(signingToken, verifier);
            }
        }
    }

    DecodedJWT jwt = verifier.verify(tokenString);
    return jwt;
}
 
Example #13
Source File: JWTSsoService.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String readUserIdentifier(HttpServletRequest request) {
	try {
		String jwtToken = request.getParameter(SsoServiceInterface.USER_ID);
		if (jwtToken == null) {
			logger.debug("JWT token not found in request");
			return null;
		}
		LogMF.debug(logger, "JWT token in input is [{0}]", jwtToken);
		JWTVerifier verifier = JWT.require(algorithm).build();
		DecodedJWT decodedJWT = verifier.verify(jwtToken);
		logger.debug("JWT token verified properly");
		Claim userIdClaim = decodedJWT.getClaim(SsoServiceInterface.USER_ID);
		LogMF.debug(logger, "User id detected is [{0}]", userIdClaim.asString());
		assertNotEmpty(userIdClaim, "User id information is missing!!!");
		return jwtToken;
	} catch (JWTVerificationException e) {
		throw new SpagoBIRuntimeException("Invalid JWT token!", e);
	}
}
 
Example #14
Source File: AuthenticationJsonWebTokenTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldNotAllowToChangeAuthenticatedToTrue() throws Exception {
    String token = JWT.create()
            .sign(hmacAlgorithm);

    JWTVerifier verifier = JWT.require(hmacAlgorithm).build();
    AuthenticationJsonWebToken auth = new AuthenticationJsonWebToken(token, verifier);
    assertThat(auth, is(notNullValue()));
    assertThat(auth.isAuthenticated(), is(true));

    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Must create a new instance to specify that the authentication is valid");
    auth.setAuthenticated(true);
}
 
Example #15
Source File: JWTAuthenticationFilter.java    From waltz with Apache License 2.0 5 votes vote down vote up
private JWTVerifier selectVerifier(DecodedJWT decodedToken) {
    String algorithm = decodedToken.getAlgorithm();
    switch (algorithm) {
        case "HS256":
            return verifier256;
        case "HS512":
            return verifier512;
        default:
            throw new IllegalStateException("Cannot verify against algorithm: " + algorithm);
    }
}
 
Example #16
Source File: AuthenticationFactory.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 校验Token
 *
 * @param token
 * @return
 * @throws Exception
 */
public static Map<String, String> verifyToken(String token) throws Exception {
    String jwtSecret = MappingCache.getValue(MappingConstant.KEY_JWT_SECRET);
    if (StringUtil.isNullOrNone(jwtSecret)) {
        jwtSecret = CommonConstant.DEFAULT_JWT_SECRET;
    }
    Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer("java110").build();
    DecodedJWT jwt = verifier.verify(token);
    String jdi = jwt.getId();
    //保存token Id
    String userId = JWTCache.getValue(jdi);
    if (StringUtil.isNullOrNone(userId)) {
        throw new JWTVerificationException("用户还未登录");
    }
    String expireTime = MappingCache.getValue(MappingConstant.KEY_JWT_EXPIRE_TIME);
    if (StringUtil.isNullOrNone(expireTime)) {
        expireTime = CommonConstant.DEFAULT_JWT_EXPIRE_TIME;
    }
    //刷新过时时间
    JWTCache.resetExpireTime(jdi, Integer.parseInt(expireTime));
    Map<String, Claim> claims = jwt.getClaims();
    // Add the claim to request header
    Map<String, String> paramOut = new HashMap<String, String>();
    for (String key : claims.keySet()) {
        paramOut.put(key, claims.get(key).asString());
    }
    paramOut.put(CommonConstant.LOGIN_USER_ID, userId);
    return paramOut;
}
 
Example #17
Source File: JWTUtil.java    From SpringAll with MIT License 5 votes vote down vote up
/**
 * 校验 token是否正确
 *
 * @param token  密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("username", username)
                .build();
        verifier.verify(token);
        log.info("token is valid");
        return true;
    } catch (Exception e) {
        log.info("token is invalid{}", e.getMessage());
        return false;
    }
}
 
Example #18
Source File: JwtUtil.java    From wetech-admin with MIT License 5 votes vote down vote up
/**
 * 校验token是否正确
 *
 * @param token
 * @return
 */
public static boolean verify(String token) {
    String secret = getClaim(token, ACCOUNT) + SECRET_KEY;
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTVerifier verifier = JWT.require(algorithm)
            .build();
    verifier.verify(token);
    return true;
}
 
Example #19
Source File: Auth0VerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    Algorithm algorithm = Algorithm.RSA256(publicKey, null);
    Verification builder = JWT.require(algorithm)
        .withIssuer(issuer);
    if(expGracePeriodSecs > 0) {
        builder = builder.acceptLeeway(expGracePeriodSecs);
    }
    JWTVerifier verifier = builder.build();
    DecodedJWT jwt = verifier.verify(token);
}
 
Example #20
Source File: JwtHelper.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
public static boolean verify(String token, User user, boolean checkExpire) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(user.getPasswordOnMd5());
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();

        verifier.verify(token);
        return true;
    } catch (JWTVerificationException e) {
        if (e instanceof TokenExpiredException) {
            return !checkExpire;
        }
        return false;
    }
}
 
Example #21
Source File: TestAlgorithmLinker.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected=com.auth0.jwt.exceptions.SignatureVerificationException.class)
public void testWithFalseKey() throws IllegalArgumentException, UnsupportedEncodingException {
	CustomJWToken tokenObj = new CustomJWToken(TestTokens.hs256_token);
	JWTVerifier verifier = JWT.require(AlgorithmLinker.getVerifierAlgorithm(tokenObj.getAlgorithm(), "invalid")).build();
	DecodedJWT test = verifier.verify(TestTokens.hs256_token);
	test.getAlgorithm();
}
 
Example #22
Source File: JwtUtil.java    From demo-project with MIT License 5 votes vote down vote up
/**
 * Description: 解密jwt
 *
 * @param token  token
 * @param secret secret
 * @return java.util.Map<java.lang.String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               com.auth0.jwt.interfaces.Claim>
 * @author fanxb
 * @date 2019/3/4 18:14
 */
public static Map<String, Claim> decode(String token, String secret) {
    if (token == null || token.length() == 0) {
        throw new CustomException("token为空:" + token);
    }
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTVerifier jwtVerifier = JWT.require(algorithm).build();
    DecodedJWT decodedJWT = jwtVerifier.verify(token);
    return decodedJWT.getClaims();
}
 
Example #23
Source File: JWTSsoService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String jwtToken2userId(String jwtToken) throws JWTVerificationException {
	LogMF.debug(logger, "JWT token in input is [{0}]", jwtToken);
	JWTVerifier verifier = JWT.require(algorithm).build();
	DecodedJWT decodedJWT = verifier.verify(jwtToken);
	logger.debug("JWT token verified properly");
	Claim userIdClaim = decodedJWT.getClaim(SsoServiceInterface.USER_ID);
	LogMF.debug(logger, "User id detected is [{0}]", userIdClaim.asString());
	assertNotEmpty(userIdClaim, "User id information is missing!!!");
	String userId = userIdClaim.asString();
	LogMF.debug(logger, "User id is [{0}]", userId);
	return userId;
}
 
Example #24
Source File: OAuth2AuthenticationResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
    TokenEntity responseToken = response.readEntity(TokenEntity.class);
    assertEquals("BEARER", responseToken.getType().name());

    String token = responseToken.getToken();

    Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
    JWTVerifier jwtVerifier = JWT.require(algorithm).build();

    DecodedJWT jwt = jwtVerifier.verify(token);

    assertEquals(jwt.getSubject(),"[email protected]");

    assertEquals(jwt.getClaim("firstname").asString(),"Jane");
    assertEquals(jwt.getClaim("iss").asString(),"gravitee-management-auth");
    assertEquals(jwt.getClaim("sub").asString(),"[email protected]");
    assertEquals(jwt.getClaim("email").asString(),"[email protected]");
    assertEquals(jwt.getClaim("lastname").asString(),"Doe");
}
 
Example #25
Source File: JWTTokenAsUserUniqueIdentifierSsoService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public void validateTicket(String ticket, String userId) throws SecurityException {
	try {
		String jwtToken = ticket;
		logger.debug("JWT token in input : [" + jwtToken + "]");
		JWTVerifier verifier = JWT.require(algorithm).withIssuer("knowage").build();
		verifier.verify(jwtToken);
		logger.debug("JWT token verified properly");
	} catch (JWTVerificationException e) {
		throw new SecurityException("Invalid JWT token!", e);
	}
}
 
Example #26
Source File: JwtVerifier.java    From curiostack with MIT License 5 votes vote down vote up
public CompletableFuture<DecodedJWT> verify(String token) {
  final DecodedJWT unverifiedJwt;
  try {
    unverifiedJwt = JWT.decode(token);
  } catch (JWTVerificationException e) {
    return CompletableFuturesExtra.exceptionallyCompletedFuture(e);
  }
  return getAlgorithm(unverifiedJwt.getKeyId())
      .thenApply(
          alg -> {
            JWTVerifier verifier = JWT.require(alg).build();
            return verifier.verify(token);
          });
}
 
Example #27
Source File: AuthenticationService.java    From clouditor with Apache License 2.0 5 votes vote down vote up
public User verifyToken(String token) {
  try {
    Algorithm algorithm = Algorithm.HMAC256(this.engine.getApiSecret());

    JWTVerifier verifier =
        JWT.require(algorithm).withIssuer(ISSUER).build(); // Reusable verifier instance
    DecodedJWT jwt = verifier.verify(token);

    var user = PersistenceManager.getInstance().getById(User.class, jwt.getSubject());

    if (user == null) {
      throw new NotAuthorizedException(ERROR_MESSAGE_USER_NOT_FOUND);
    }

    return user;
  } catch (JWTVerificationException ex) {
    throw new NotAuthorizedException("Invalid token", ex);
  }
}
 
Example #28
Source File: TestAlgorithmLinker.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testWithProperKey() throws IllegalArgumentException, UnsupportedEncodingException {
	CustomJWToken tokenObj = new CustomJWToken(TestTokens.hs256_token);
	JWTVerifier verifier = JWT.require(AlgorithmLinker.getVerifierAlgorithm(tokenObj.getAlgorithm(), "secret")).build();
	DecodedJWT test = verifier.verify(TestTokens.hs256_token);
	test.getAlgorithm();
}
 
Example #29
Source File: JwtUtil.java    From bookmark with MIT License 5 votes vote down vote up
/**
 * Description: 解密jwt
 *
 * @param token  token
 * @param secret secret
 * @return java.util.Map<java.lang.String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               com.auth0.jwt.interfaces.Claim>
 * @author fanxb
 * @date 2019/3/4 18:14
 */
public static Map<String, Claim> decode(String token, String secret) {
    if (token == null || token.length() == 0) {
        throw new CustomException("token为空:" + token);
    }
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTVerifier jwtVerifier = JWT.require(algorithm).build();
    DecodedJWT decodedJWT = jwtVerifier.verify(token);
    return decodedJWT.getClaims();
}
 
Example #30
Source File: JwtUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 校验token是否正确
 *
 * @param token  密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
	try {
		// 根据密码生成JWT效验器
		Algorithm algorithm = Algorithm.HMAC256(secret);
		JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
		// 效验TOKEN
		DecodedJWT jwt = verifier.verify(token);
		return true;
	} catch (Exception exception) {
		return false;
	}
}