Search in sources :

Example 6 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project java-rest-api by messagebird.

the class RequestValidator method validateSignature.

/**
 * Returns raw signature payload after validating a signature successfully,
 * otherwise throws {@code RequestValidationException}.
 * <p>
 * This JWT is signed with a MessageBird account unique secret key, ensuring the request is from MessageBird and
 * a specific account.
 * The JWT contains the following claims:
 * </p>
 * <ul>
 *   <li>"url_hash" - the raw URL hashed with SHA256 ensuring the URL wasn't altered.</li>
 *   <li> "payload_hash" - the raw payload hashed with SHA256 ensuring the payload wasn't altered.</li>
 *   <li> "jti" - a unique token ID to implement an optional non-replay check (NOT validated by default).</li>
 *   <li> "nbf" - the not before timestamp.</li>
 *   <li> "exp" - the expiration timestamp is ensuring that a request isn't captured and used at a later time.</li>
 *   <li> "iss" - the issuer name, always MessageBird.</li>
 * </ul>
 *
 * @param clock       custom {@link Clock} instance to validate timestamp claims.
 * @param signature   the actual signature.
 * @param url         the raw url including the protocol, hostname and query string,
 *                    {@code https://example.com/?example=42}.
 * @param requestBody the raw request body.
 * @return raw signature payload as {@link DecodedJWT} object.
 * @throws RequestValidationException when the signature is invalid.
 * @see <a href="https://developers.messagebird.com/docs/verify-http-requests">Verify HTTP Requests</a>
 */
public DecodedJWT validateSignature(Clock clock, String signature, String url, byte[] requestBody) throws RequestValidationException {
    if (signature == null || signature.length() == 0)
        throw new RequestValidationException("The signature can not be empty.");
    if (!skipURLValidation && (url == null || url.length() == 0))
        throw new RequestValidationException("The url can not be empty.");
    DecodedJWT jwt = JWT.decode(signature);
    Algorithm algorithm;
    switch(jwt.getAlgorithm()) {
        case "HS256":
            algorithm = HMAC256;
            break;
        case "HS384":
            algorithm = HMAC384;
            break;
        case "HS512":
            algorithm = HMAC512;
            break;
        default:
            throw new RequestValidationException(String.format("The signing method '%s' is invalid.", jwt.getAlgorithm()));
    }
    BaseVerification builder = (BaseVerification) JWT.require(algorithm).withIssuer("MessageBird").ignoreIssuedAt().acceptLeeway(1);
    if (!skipURLValidation)
        builder.withClaim("url_hash", calculateSha256(url.getBytes()));
    boolean payloadHashClaimExist = !jwt.getClaim("payload_hash").isNull();
    if (requestBody != null && requestBody.length > 0) {
        if (!payloadHashClaimExist) {
            throw new RequestValidationException("The Claim 'payload_hash' is not set but payload is present.");
        }
        builder.withClaim("payload_hash", calculateSha256(requestBody));
    } else if (payloadHashClaimExist) {
        throw new RequestValidationException("The Claim 'payload_hash' is set but actual payload is missing.");
    }
    JWTVerifier verifier = clock == null ? builder.build() : builder.build(clock);
    try {
        return verifier.verify(jwt);
    } catch (SignatureVerificationException e) {
        throw new RequestValidationException("Signature is invalid.", e);
    } catch (JWTVerificationException e) {
        throw new RequestValidationException(e.getMessage(), e.getCause());
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) RequestValidationException(com.messagebird.exceptions.RequestValidationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) BaseVerification(com.auth0.jwt.JWTVerifier.BaseVerification)

Example 7 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project gravitee-management-rest-api by gravitee-io.

the class OAuth2AuthenticationResourceTest method verifyJwtToken.

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(), "janedoe@example.com");
    assertEquals(jwt.getClaim("firstname").asString(), "Jane");
    assertEquals(jwt.getClaim("iss").asString(), "gravitee-management-auth");
    assertEquals(jwt.getClaim("sub").asString(), "janedoe@example.com");
    assertEquals(jwt.getClaim("email").asString(), "janedoe@example.com");
    assertEquals(jwt.getClaim("lastname").asString(), "Doe");
}
Also used : TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 8 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project VX-API-Gateway by EliMirren.

the class VxApiAuthJwtTokenImpl method handle.

@Override
public void handle(RoutingContext event) {
    String token = event.request().getHeader(apiTokenName);
    String username = event.request().getHeader(userTokenName);
    String userKey = null;
    if (username == null || username.equals("")) {
        event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
    }
    for (Object object : userKeys) {
        if (object instanceof JsonObject) {
            if (((JsonObject) object).getString(username) instanceof String) {
                userKey = ((JsonObject) object).getString(username);
            }
        }
    }
    LOG.info("userKey:" + userKey);
    if (userKey == null || userKey.equals("")) {
        event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
    }
    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(userKey)).build();
    DecodedJWT jwt = null;
    try {
        jwt = verifier.verify(token);
        event.next();
    } catch (Exception e) {
        event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
    // throw new RuntimeException("凭证无效或己过期!");
    }
/*
		Session session = event.session();
		if (session == null) {
			event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
					.putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
		} else {
			// session中的token
			String apiToken = session.get(apiTokenName) == null ? null : session.get(apiTokenName).toString();
			// 用户request中的token
			String userTokoen = null;
			if (userTokenScope == ParamPositionEnum.HEADER) {
				userTokoen = event.request().getHeader(userTokenName);
			} else {
				userTokoen = event.request().getParam(userTokenName);
			}
			// 检验请求是否正确如果正确放行反则不通过
			if (!StrUtil.isNullOrEmpty(apiToken) && apiToken.equals(userTokoen)) {
				event.next();
			} else {
				event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
						.putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
			}
		}
		*/
}
Also used : JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 9 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project gravitee-api-management by gravitee-io.

the class OAuth2AuthenticationResourceTest method verifyJwtToken.

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(), "janedoe@example.com");
    assertEquals(jwt.getClaim("firstname").asString(), "Jane");
    assertEquals(jwt.getClaim("iss").asString(), "gravitee-management-auth");
    assertEquals(jwt.getClaim("sub").asString(), "janedoe@example.com");
    assertEquals(jwt.getClaim("email").asString(), "janedoe@example.com");
    assertEquals(jwt.getClaim("lastname").asString(), "Doe");
}
Also used : TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 10 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project jeecg-boot by jeecgboot.

the class JwtUtil method verify.

/**
 * 校验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;
    }
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IOException(java.io.IOException) JeecgBootException(org.jeecg.common.exception.JeecgBootException) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException)

Aggregations

JWTVerifier (com.auth0.jwt.JWTVerifier)86 Algorithm (com.auth0.jwt.algorithms.Algorithm)79 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)73 Test (org.junit.Test)36 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)27 IOException (java.io.IOException)18 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)12 RSAPublicKey (java.security.interfaces.RSAPublicKey)11 Claim (com.auth0.jwt.interfaces.Claim)9 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)8 Date (java.util.Date)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 HashMap (java.util.HashMap)6 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 KeyFactory (java.security.KeyFactory)4 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)4 Bean (org.springframework.context.annotation.Bean)4 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)3