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());
}
}
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");
}
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);
}
}
*/
}
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");
}
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;
}
}
Aggregations