Java Code Examples for com.auth0.jwt.JWTVerifier#verify()

The following examples show how to use com.auth0.jwt.JWTVerifier#verify() . 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: 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 2
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 3
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 4
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 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: 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 7
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 8
Source File: JWTUtil.java    From permission 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();
        // 效验TOKEN
        verifier.verify(token);
        return true;
    } catch (Exception e) {
        log.info("token is invalid{}", e.getMessage());
        return false;
    }
}
 
Example 9
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 10
Source File: AuthSign.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**校验token
 *
 * @param token
 * @return
 */
public  static  boolean verify(String token) {
    try {
        Algorithm algorithm= Algorithm.HMAC256(SECRET);
        JWTVerifier verifier=JWT.require(algorithm).build();
        DecodedJWT jwt=verifier.verify(token);
        return true;
    } catch (Exception e) {
        log.info("token校验失败:"+ExceptionUtils.getStackTrace(e));
        return false;
    }

}
 
Example 11
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 12
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;
	}
}
 
Example 13
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 14
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 15
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 16
Source File: JwtUtil.java    From jeecg-boot-with-activiti 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 {
		// 根据密码生成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;
	}
}
 
Example 17
Source File: AuthSign.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * 获取用户信息
 */
public  static JSONObject  getUserObject(String token) {
    try {
        Algorithm algorithm= Algorithm.HMAC256(SECRET);
        JWTVerifier verifier=JWT.require(algorithm).build();
        DecodedJWT jwt=verifier.verify(token);
        return JSONObject.parseObject(jwt.getClaim(OBJECT).asString());
    } catch (Exception e) {
        log.info("获取用户id错误:%s", ExceptionUtils.getStackTrace(e));
    }
    return null;
}
 
Example 18
Source File: JwtUtil.java    From SpringBoot-Home with Apache License 2.0 4 votes vote down vote up
/**
 * 校验token
 * @param token
 * @return
 */
public static boolean checkSign(String token) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier verifier = JWT.require(algorithm)
                // .withClaim("username", username)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        return true;
    } catch (JWTVerificationException exception) {
        throw new RuntimeException("token 无效,请重新获取");
    }
}
 
Example 19
Source File: JwtUtil.java    From Moss with Apache License 2.0 4 votes vote down vote up
/**
 * 校验 token 是否正确
 *
 * @param token    密钥
 * @param username 用户名
 * @return 是否正确
 */
public static boolean verify(String token, String username) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        //在token中附带了username信息
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("username", username)
                .build();
        //验证 token
        verifier.verify(token);
        return true;
    } catch (Exception exception) {
        return false;
    }
}
 
Example 20
Source File: JwtUtil.java    From ProjectStudy with MIT License 4 votes vote down vote up
/**
 * 校验token是否正确
 *
 * @param token  Token
 * @param secret 私钥
 * @return boolean 是否正确
 * @author Wang926454
 * @date 2018/8/31 9:05
 */
public static boolean verify(String token, String secret) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        return true;
    } catch (UnsupportedEncodingException e) {
        e.getMessage();
    }
    return false;
}