use of com.auth0.jwt.Claim in project ofbiz-framework by apache.
the class JWTManager method validateToken.
/**
* Validates the provided token using the secret key.
* If the token is valid it will get the conteined claims and return them.
* If token validation failed it will return an error.
* Public for API access from third party code.
* @param jwtToken the JWT token
* @param key the server side key to verify the signature
* @return Map of the claims contained in the token or an error
*/
public static Map<String, Object> validateToken(String jwtToken, String key) {
Map<String, Object> result = new HashMap<>();
if (UtilValidate.isEmpty(jwtToken) || UtilValidate.isEmpty(key)) {
String msg = "JWT token or key can not be empty.";
Debug.logError(msg, MODULE);
return ServiceUtil.returnError(msg);
}
try {
JWTVerifier verifToken = JWT.require(Algorithm.HMAC512(key)).withIssuer("ApacheOFBiz").build();
DecodedJWT jwt = verifToken.verify(jwtToken);
Map<String, Claim> claims = jwt.getClaims();
// OK, we can trust this JWT
for (Map.Entry<String, Claim> entry : claims.entrySet()) {
result.put(entry.getKey(), entry.getValue().asString());
}
return result;
} catch (JWTVerificationException e) {
// signature not valid or token expired
Debug.logError(e.getMessage(), MODULE);
return ServiceUtil.returnError(e.getMessage());
}
}
use of com.auth0.jwt.Claim in project litemall by linlinjava.
the class JwtHelper method verifyTokenAndGetUserId.
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;
}
use of com.auth0.jwt.Claim in project opencast by opencast.
the class JWTVerifierTest method testVerifyAsymmetric.
@Test
public void testVerifyAsymmetric() throws Exception {
DecodedJWT decodedJWT;
// Valid JWT + valid claim constraints
decodedJWT = JWTVerifier.verify(generator.generateValidAsymmetricJWT(), validProvider, generator.generateValidClaimConstraints());
assertEquals(generator.getUsername(), decodedJWT.getClaim("username").asString());
// Valid JWT + invalid claim constraints
assertThrows(JWTVerificationException.class, () -> JWTVerifier.verify(generator.generateValidAsymmetricJWT(), validProvider, generator.generateInvalidClaimConstraints()));
// Valid JWT + invalid provider
assertThrows(JWTVerificationException.class, () -> JWTVerifier.verify(generator.generateValidAsymmetricJWT(), invalidProvider, generator.generateValidClaimConstraints()));
// Invalid JWT
assertThrows(JWTVerificationException.class, () -> JWTVerifier.verify(generator.generateExpiredAsymmetricJWT(), validProvider, generator.generateValidClaimConstraints()));
// Simulate key rotation
decodedJWT = JWTVerifier.verify(generator.generateValidAsymmetricJWT(), rotatingProvider, generator.generateValidClaimConstraints());
assertEquals(generator.getUsername(), decodedJWT.getClaim("username").asString());
}
use of com.auth0.jwt.Claim in project hopsworks by logicalclocks.
the class JWTController method invalidateServiceToken.
public void invalidateServiceToken(String serviceToken2invalidate, String defaultJWTSigningKeyName) {
DecodedJWT serviceJWT2invalidate = decodeToken(serviceToken2invalidate);
try {
invalidate(serviceToken2invalidate);
} catch (InvalidationException ex) {
LOGGER.log(Level.WARNING, "Could not invalidate service JWT with ID " + serviceJWT2invalidate.getId() + ". Continuing with deleting signing key");
}
Claim signingKeyID = serviceJWT2invalidate.getClaim(Constants.SERVICE_JWT_RENEWAL_KEY_ID);
if (signingKeyID != null && !signingKeyID.isNull()) {
// Do not use Claim.asInt, it returns null
JwtSigningKey signingKey = findSigningKeyById(Integer.parseInt(signingKeyID.asString()));
if (signingKey != null && defaultJWTSigningKeyName != null) {
if (!defaultJWTSigningKeyName.equals(signingKey.getName()) && !ONE_TIME_JWT_SIGNING_KEY_NAME.equals(signingKey.getName())) {
deleteSigningKey(signingKey.getName());
}
}
}
}
use of com.auth0.jwt.Claim in project hopsworks by logicalclocks.
the class JWTFilter method jwtFilter.
public void jwtFilter(ContainerRequestContext requestContext) throws IOException {
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
Object responseEntity;
if (authorizationHeader == null) {
LOGGER.log(Level.FINEST, "Authorization header not set.");
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Authorization header not set.");
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
if (!authorizationHeader.startsWith(BEARER)) {
LOGGER.log(Level.FINEST, "Invalid token. AuthorizationHeader : {0}", authorizationHeader);
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
String token = authorizationHeader.substring(BEARER.length()).trim();
DecodedJWT jwt = JWT.decode(token);
Claim expLeewayClaim = jwt.getClaim(EXPIRY_LEEWAY);
String issuer = getIssuer();
int expLeeway = expLeewayClaim.asInt();
try {
Algorithm algorithm = getAlgorithm(jwt);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer == null || issuer.isEmpty() ? jwt.getIssuer() : issuer).acceptExpiresAt(expLeeway == 0 ? DEFAULT_EXPIRY_LEEWAY : expLeeway).build();
jwt = verifier.verify(token);
} catch (Exception exception) {
LOGGER.log(Level.FINE, "JWT Verification Exception: {0}", exception.getMessage());
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, exception.getMessage());
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
if (!isTokenValid(jwt)) {
LOGGER.log(Level.FINEST, "JWT Verification Exception: Invalidated token.");
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
Claim rolesClaim = jwt.getClaim(ROLES);
String[] userRoles = rolesClaim == null ? new String[0] : rolesClaim.asArray(String.class);
Set<String> allowedRolesSet = allowedRoles();
if (allowedRolesSet != null && !allowedRolesSet.isEmpty()) {
if (!intersect(allowedRolesSet, Arrays.asList(userRoles))) {
LOGGER.log(Level.FINE, "JWT Access Exception: Client not authorized for this invocation.");
responseEntity = responseEntity(Response.Status.FORBIDDEN, "Client not authorized for this invocation.");
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
return;
}
}
List<String> audience = jwt.getAudience();
Set<String> accepts = acceptedTokens();
if (accepts != null && !accepts.isEmpty()) {
if (!intersect(accepts, audience)) {
LOGGER.log(Level.FINE, "JWT Access Exception: Token not issued for this recipient.");
responseEntity = responseEntity(Response.Status.FORBIDDEN, "Token not issued for this recipient.");
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
return;
}
}
postJWTFilter(requestContext, jwt);
}
Aggregations