com.auth0.jwt.exceptions.JWTVerificationException Java Examples
The following examples show how to use
com.auth0.jwt.exceptions.JWTVerificationException.
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: JwtAuthenticationServiceImpl.java From alibaba-rsocket-broker with Apache License 2.0 | 6 votes |
@Override public @Nullable NamedPrincipal auth(String jwtToken) { int tokenHashCode = jwtToken.hashCode(); NamedPrincipal principal = jwtVerifyCache.getIfPresent(tokenHashCode); if (principal == null) { for (JWTVerifier verifier : verifiers) { try { DecodedJWT decodedJWT = verifier.verify(jwtToken); principal = new NamedPrincipal(decodedJWT.getSubject()); jwtVerifyCache.put(tokenHashCode, principal); break; } catch (JWTVerificationException ignore) { } } } return principal; }
Example #2
Source File: SignatureVerifier.java From auth0-java with MIT License | 6 votes |
/** * Verifies a token's signature. * * @param token the token for which to verify its signature. * @return a {@linkplain DecodedJWT} that represents the token. * @throws IdTokenValidationException if the signature verification failed. */ DecodedJWT verifySignature(String token) throws IdTokenValidationException { DecodedJWT decoded = decodeToken(token); try { this.verifier.verify(decoded); } catch (AlgorithmMismatchException algorithmMismatchException) { String message = String.format("Signature algorithm of \"%s\" is not supported. Expected the ID token to be signed with \"%s\"", decoded.getAlgorithm(), this.algorithm.getName()); throw new IdTokenValidationException(message, algorithmMismatchException); } catch (SignatureVerificationException signatureVerificationException) { throw new IdTokenValidationException("Invalid ID token signature", signatureVerificationException); } catch (JWTVerificationException ignored) { // no-op. Would only occur for expired tokens, which will be handle during claims validation } return decoded; }
Example #3
Source File: JWTFilter.java From spring-jwt-gateway with Apache License 2.0 | 6 votes |
@Override public GatewayFilter apply(NameValueConfig config) { return (exchange, chain) -> { try { String token = this.extractJWTToken(exchange.getRequest()); DecodedJWT decodedJWT = this.jwtVerifier.verify(token); ServerHttpRequest request = exchange.getRequest().mutate(). header(X_JWT_SUB_HEADER, decodedJWT.getSubject()). build(); return chain.filter(exchange.mutate().request(request).build()); } catch (JWTVerificationException ex) { logger.error(ex.toString()); return this.onError(exchange, ex.getMessage()); } }; }
Example #4
Source File: TaskController.java From onenet-iot-project with MIT License | 6 votes |
/** * 通过任务 ID 获取任务生产进度 * * @param request 请求 * @param taskId 任务 ID * @return Response */ @GetMapping("/{taskId}/process") public Response getTaskProcess(HttpServletRequest request, @PathVariable String taskId) { String token = request.getHeader("token"); if (!VerifyUtil.checkString(taskId, token)) { return ResultUtil.returnStatus(ResponseStatus.PARAMS_ERROR); } else { try { // 解析token Claim claim = tokenUtil.getClaim(token, "account_id"); Account account = accountService.findAccountById(claim.asString()); // 判断角色是否有权限 if (account != null && account.getRole() == Role.ADMIN) { Map<String, Object> status = taskService.getStatus(taskId); log.info("get status: {}", status); return ResultUtil.returnStatusAndData(ResponseStatus.SUCCESS, status); } else { return ResultUtil.returnStatus(ResponseStatus.VISITED_FORBID); } } catch (JWTVerificationException e) { // 解析失败,token无效 log.error("{}", e); return ResultUtil.returnStatus(ResponseStatus.NOT_LOGIN); } } }
Example #5
Source File: TokenDecoder.java From cf-java-logging-support with Apache License 2.0 | 6 votes |
/** * This method validates if a token has a valid signature as well as a valid * timestamp and returns the decoded token * * @throws DynamicLogLevelException */ public DecodedJWT validateAndDecodeToken(String token) throws DynamicLogLevelException { try { DecodedJWT jwt = verifier.verify(token); Date exp = jwt.getExpiresAt(); Date iat = jwt.getIssuedAt(); Date now = new Date(); if (exp != null && iat != null && now.after(iat) && now.before(exp)) { return jwt; } else { throw new DynamicLogLevelException("Token provided to dynamically change the log-level on thread-level is outdated"); } } catch (JWTVerificationException e) { // Exception is not attached to avoid logging of JWT token throw new DynamicLogLevelException("Token could not be verified"); } }
Example #6
Source File: JWTTokenAsUserUniqueIdentifierSsoService.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
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 #7
Source File: OAuth2AuthenticationResourceTest.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
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 #8
Source File: JWTGenerator.java From elepy with Apache License 2.0 | 6 votes |
@Override public Grant validateToken(String rawToken) { try { final var decodedToken = JWT.require(algorithm).build().verify(rawToken); final var userId = decodedToken.getClaim("userId").asString(); final var username = decodedToken.getClaim("username").asString(); final var permissions = decodedToken.getClaim("permissions").asList(String.class); final var grant = new Grant(); grant.setPermissions(permissions); grant.setUserId(userId); grant.setUsername(username); return grant; } catch (JWTVerificationException e) { return null; } }
Example #9
Source File: SecureServerComms.java From vicinity-gateway-api with GNU General Public License v3.0 | 6 votes |
public String loadToken(File file) { // loaded data String token; try { InputStream is = new FileInputStream(file); token = IOUtils.toString(is, "UTF-8"); is.close(); verifyToken(token); } catch (IOException i) { logger.warning("Token could not be loaded from file, creating new one..."); i.printStackTrace(); token = generateToken(); return token; } catch (JWTVerificationException jwte){ //Invalid signature/claims logger.warning("Error verifying file token, creating new one..."); jwte.printStackTrace(); token = generateToken(); return token; } catch (Exception e) { e.printStackTrace(); return null; } return token; }
Example #10
Source File: JwtApplication.java From spring-boot-study with MIT License | 6 votes |
/** * 验证 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 #11
Source File: MachineController.java From onenet-iot-project with MIT License | 6 votes |
/** * 获取机器设备列表 * * @param request 请求 * @return Response */ @GetMapping public Response getMachineList(HttpServletRequest request) { String token = request.getHeader("token"); if (!VerifyUtil.checkString(token)) { return ResultUtil.returnStatus(ResponseStatus.NOT_LOGIN); } else { try { // 解析token Claim claim = tokenUtil.getClaim(token, "account_id"); Account account = accountService.findAccountById(claim.asString()); // 判断角色是否有权限 if (account != null && account.getRole() == Role.ADMIN) { List<Machine> machines = machineService.findAllMachine(); log.info("machines: {}", machines); return ResultUtil.returnStatusAndData(ResponseStatus.SUCCESS, machines); } else { return ResultUtil.returnStatus(ResponseStatus.VISITED_FORBID); } } catch (JWTVerificationException e) { // 解析失败,token无效 log.error("{}", e); return ResultUtil.returnStatus(ResponseStatus.NOT_LOGIN); } } }
Example #12
Source File: AuthenticationServiceJwtImpl.java From alibaba-rsocket-broker with Apache License 2.0 | 6 votes |
@Override @Nullable public RSocketAppPrincipal auth(String type, String credentials) { int tokenHashCode = credentials.hashCode(); RSocketAppPrincipal principal = jwtVerifyCache.getIfPresent(tokenHashCode); for (JWTVerifier verifier : verifiers) { try { principal = new JwtPrincipal(verifier.verify(credentials), credentials); jwtVerifyCache.put(tokenHashCode, principal); break; } catch (JWTVerificationException ignore) { } } return principal; }
Example #13
Source File: SignatureVerifier.java From auth0-java-mvc-common with MIT License | 6 votes |
DecodedJWT verifySignature(String token) throws TokenValidationException { DecodedJWT decoded = decodeToken(token); if (!this.acceptedAlgorithms.contains(decoded.getAlgorithm())) { throw new TokenValidationException(String.format("Signature algorithm of \"%s\" is not supported. Expected the ID token to be signed with \"%s\".", decoded.getAlgorithm(), this.acceptedAlgorithms)); } if (verifier != null) { try { verifier.verify(decoded); } catch (SignatureVerificationException e) { throw new TokenValidationException("Invalid token signature", e); } catch (JWTVerificationException ignored) { //NO-OP. Will be catch on a different step //Would only trigger for "expired tokens" (invalid exp) } } return decoded; }
Example #14
Source File: JwtHelper.java From litemall with MIT License | 5 votes |
public Integer verifyTokenAndGetUserId(String token) { try { Algorithm algorithm = Algorithm.HMAC256(SECRET); JWTVerifier verifier = JWT.require(algorithm) .withIssuer(ISSUSER) .build(); DecodedJWT jwt = verifier.verify(token); Map<String, Claim> claims = jwt.getClaims(); Claim claim = claims.get("userId"); return claim.asInt(); } catch (JWTVerificationException exception){ // exception.printStackTrace(); } return 0; }
Example #15
Source File: JWTTokenManager.java From data-transfer-project with Apache License 2.0 | 5 votes |
@Override public UUID getJobIdFromToken(String token) { try { DecodedJWT jwt = verifier.verify(token); // Token is verified, get claim Claim claim = jwt.getClaim(JWTTokenManager.ID_CLAIM_KEY); if (claim.isNull()) { return null; } return claim.isNull() ? null : UUID.fromString(claim.asString()); } catch (JWTVerificationException exception) { monitor.debug(() -> "Error verifying token", exception); throw new RuntimeException("Error verifying token: " + token); } }
Example #16
Source File: SignupJWTTokenManager.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
public static String verifyJWTToken(String token) throws TokenExpiredException, SecurityException{ try { String jwtToken = token; return JWTSsoService.jwtToken2userId(jwtToken); }catch (TokenExpiredException te) { throw te; }catch (JWTVerificationException e) { throw new SecurityException("Invalid JWT token!", e); } }
Example #17
Source File: SecureServerComms.java From vicinity-gateway-api with GNU General Public License v3.0 | 5 votes |
private void verifyToken(String token) throws JWTVerificationException, IOException{ String file = path + pubKey; try { RSAPublicKey publicKey = readPublicKey(file); //Get the key instance Algorithm algorithm = Algorithm.RSA256(publicKey, null); JWTVerifier verifier = JWT.require(algorithm) .withIssuer(agid) .build(); //Reusable verifier instance DecodedJWT jwt = verifier.verify(token); logger.fine("Token expires at: " + jwt.getExpiresAt().toString()); } catch (Exception e) { e.printStackTrace(); } }
Example #18
Source File: AbstractJWKSTest.java From microprofile-jwt-auth with Apache License 2.0 | 5 votes |
/** * Ensure a token is validated by the provider using the JWKS URL for the public key associated * with the signer. * * @throws Exception */ @Test(expectedExceptions = {InvalidJwtException.class, BadJOSEException.class, JWTVerificationException.class}) public void testNoMatchingKID() throws Exception { PrivateKey pk = loadPrivateKey(); String token = TokenUtils.generateTokenString(pk, "invalid-kid", "/Token1.json", null, null); int expGracePeriodSecs = 60; validateToken(token, new URL(endpoint), TEST_ISSUER, expGracePeriodSecs); }
Example #19
Source File: AuthServiceImpl.java From smockin with Apache License 2.0 | 5 votes |
public void verifyToken(final String jwt) throws AuthException { try { jwtVerifier.verify(jwt); } catch (JWTVerificationException ex) { logger.debug("JWT authorization failed", ex); throw new AuthException(); } }
Example #20
Source File: JwtHelper.java From flow-platform-x with Apache License 2.0 | 5 votes |
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: JwtTokenUtil.java From sakai with Educational Community License v2.0 | 5 votes |
private JWT decodeToken(String token) { JWT jwt = null; try { jwt = JWT.decode(token); // First verify it JWTVerifier verifier = JWT.require(Algorithm.HMAC256( serverConfigurationService.getString(rubricsConfiguration.RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY, rubricsConfiguration.RUBRICS_TOKEN_SIGNING_SHARED_SECRET_DEFAULT))) .build(); //Reusable verifier instance verifier.verify(token); } catch (UnsupportedEncodingException | JWTVerificationException e) { // If expired, check if the session is still live in the sakai system // we can do this because the first exception to be launched is the signature verification failure // So if the exception is only about token expiring we can be sure the token was a correct one. if (!(e.getMessage().startsWith("The Token has expired on") && isSakaiSessionStillValid(jwt.getClaim("sessionId").asString()))) { throw new JwtTokenMalformedException(String.format("Error occurred while decoding access token '%s'", token), e); } } // Manually verify audience and issuer since we are using the validation error flow to allow for time // extensions - in lieu of just specifying withAudience(JWT_AUDIENCE).withIssuer(JWT_ISSUER) to the Verifier if (!jwt.getAudience().contains(JWT_AUDIENCE)) { throw new JwtTokenMalformedException(String.format("Access token denied for audience. Expected: ['%s'], " + "Provided: %s, Token: %s", JWT_AUDIENCE, jwt.getAudience().toString(), token)); } if (!jwt.getIssuer().contentEquals(JWT_ISSUER)) { throw new JwtTokenMalformedException(String.format("Access token denied for issuer. Expected: ['%s'], " + "Provided: %s, Token: %s", JWT_ISSUER, jwt.getIssuer().toString(), token)); } return jwt; }
Example #22
Source File: JWTSsoService.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
@Override 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 #23
Source File: AuthenticationFactory.java From MicroCommunity with Apache License 2.0 | 5 votes |
/** * 校验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 #24
Source File: RetestAuthentication.java From recheck with GNU Affero General Public License v3.0 | 5 votes |
private boolean isAccessTokenValid() { try { final DecodedJWT verify = verifier.verify( accessToken ); return accessToken != null && verify != null; } catch ( final JWTVerificationException exception ) { log.info( "Current token is invalid, requesting new one" ); } return false; }
Example #25
Source File: Tools.java From flowchat with GNU General Public License v3.0 | 5 votes |
public static final DecodedJWT decodeJWTToken(String token) { DecodedJWT jwt = null; try { JWTVerifier verifier = JWT.require(getJWTAlgorithm()).withIssuer("flowchat").build(); jwt = verifier.verify(token); } catch (JWTVerificationException e) { } return jwt; }
Example #26
Source File: JwtVerifier.java From curiostack with MIT License | 5 votes |
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: JwtHelper.java From flow-platform-x with Apache License 2.0 | 5 votes |
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 #28
Source File: MCRSessionFilter.java From mycore with GNU General Public License v3.0 | 5 votes |
private static void checkIPClaim(Claim ipClaim, String remoteAddr) { try { if (ipClaim.isNull() || !MCRFrontendUtil.isIPAddrAllowed(ipClaim.asString(), remoteAddr)) { throw new JWTVerificationException( "The Claim '" + MCRJWTUtil.JWT_CLAIM_IP + "' value doesn't match the required one."); } } catch (UnknownHostException e) { throw new JWTVerificationException( "The Claim '" + MCRJWTUtil.JWT_CLAIM_IP + "' value doesn't match the required one.", e); } }
Example #29
Source File: JwtUtils.java From WeEvent with Apache License 2.0 | 5 votes |
/** * decode AccountEntity from token * f * * @param token token * @return AccountEntity */ public static AccountEntity decodeToken(String token, String privateSecret) { try { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(privateSecret)).build(); DecodedJWT jwt = verifier.verify(token); // check expired date if (Calendar.getInstance().getTime().after(jwt.getExpiresAt())) { log.error("expired token at {}", jwt.getExpiresAt()); return null; } return new AccountEntity(jwt.getIssuer()); } catch (JWTVerificationException e) { log.error("invalid jwt token", e); return null; } }
Example #30
Source File: MCRJWTResource.java From mycore with GNU General Public License v3.0 | 5 votes |
public static void validate(String token) throws JWTVerificationException { if (!Optional.of(JWT.require(MCRJWTUtil.getJWTAlgorithm()) .withAudience(AUDIENCE) .build().verify(token)) .map(DecodedJWT::getId) .map(MCRSessionMgr::getSession) .isPresent()) { throw new JWTVerificationException("MCRSession is invalid."); } }