use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.
the class TokenAuthenticationFilter method doFilter.
@Override
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String stringToken = req.getHeader(HttpHeaders.AUTHORIZATION);
if (isEmpty(stringToken) && req.getCookies() != null) {
final Optional<Cookie> optionalStringToken = Arrays.stream(req.getCookies()).filter(cookie -> AUTH_COOKIE_NAME.equals(cookie.getName())).findAny();
if (optionalStringToken.isPresent()) {
stringToken = decode(optionalStringToken.get().getValue(), defaultCharset().name());
}
}
if (isEmpty(stringToken)) {
LOGGER.debug("Authorization header/cookie not found");
} else {
try {
if (stringToken.toLowerCase().contains(TOKEN_AUTH_SCHEMA)) {
final String tokenValue = stringToken.substring(TOKEN_AUTH_SCHEMA.length()).trim();
if (tokenValue.contains(".")) {
final DecodedJWT jwt = jwtVerifier.verify(tokenValue);
final Set<GrantedAuthority> authorities = this.authoritiesProvider.retrieveAuthorities(jwt.getClaim(Claims.SUBJECT).asString());
final UserDetails userDetails = new UserDetails(getStringValue(jwt.getSubject()), "", authorities);
userDetails.setEmail(jwt.getClaim(Claims.EMAIL).asString());
userDetails.setFirstname(jwt.getClaim(Claims.FIRSTNAME).asString());
userDetails.setLastname(jwt.getClaim(Claims.LASTNAME).asString());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
} else if (tokenService != null && userService != null) {
final Token token = tokenService.findByToken(tokenValue);
final UserEntity user = userService.findById(token.getReferenceId());
final Set<GrantedAuthority> authorities = this.authoritiesProvider.retrieveAuthorities(user.getId());
final UserDetails userDetails = new UserDetails(user.getId(), "", authorities);
userDetails.setFirstname(user.getFirstname());
userDetails.setLastname(user.getLastname());
userDetails.setEmail(user.getEmail());
userDetails.setSource("token");
userDetails.setSourceId(token.getName());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
}
} else {
LOGGER.debug("Authorization schema not found");
}
} catch (final Exception e) {
final String errorMessage = "Invalid token";
if (LOGGER.isDebugEnabled()) {
LOGGER.error(errorMessage, e);
} else {
if (e instanceof JWTVerificationException) {
LOGGER.warn(errorMessage);
} else {
LOGGER.error(errorMessage);
}
}
res.addCookie(cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, null));
res.sendError(HttpStatusCode.UNAUTHORIZED_401);
return;
}
}
chain.doFilter(request, response);
}
use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.
the class UserServiceImpl method finalizeResetPassword.
@Override
public UserEntity finalizeResetPassword(ResetPasswordUserEntity registerUserEntity) {
try {
DecodedJWT jwt = getDecodedJWT(registerUserEntity.getToken());
final String action = jwt.getClaim(Claims.ACTION).asString();
if (!RESET_PASSWORD.name().equals(action)) {
throw new UserStateConflictException("Invalid action on reset password resource");
}
final Object subject = jwt.getSubject();
User user;
if (subject == null) {
throw new UserNotFoundException("Subject missing from JWT token");
} else {
final String username = subject.toString();
LOGGER.debug("Find user {} to update password", username);
Optional<User> checkUser = userRepository.findById(username);
user = checkUser.orElseThrow(() -> new UserNotFoundException(username));
}
// Set date fields
user.setUpdatedAt(new Date());
// Encrypt password if internal user
encryptPassword(user, registerUserEntity.getPassword());
user = userRepository.update(user);
auditService.createOrganizationAuditLog(Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_CHANGED, user.getUpdatedAt(), null, null);
// Do not send back the password
user.setPassword(null);
return convert(user, true);
} catch (AbstractManagementException ex) {
throw ex;
} catch (Exception ex) {
LOGGER.error("An error occurs while trying to change password of an internal user with the token {}", registerUserEntity.getToken(), ex);
throw new TechnicalManagementException(ex.getMessage(), ex);
}
}
use of com.auth0.jwt.JWT 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.JWT in project gravitee-management-rest-api by gravitee-io.
the class AbstractAuthenticationResource method connectUser.
protected Response connectUser(String userId) {
UserEntity user = userService.connect(userId);
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
Set<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities());
// We must also load permissions from repository for configured management or portal role
RoleEntity role = membershipService.getRole(MembershipReferenceType.MANAGEMENT, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.MANAGEMENT);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
role = membershipService.getRole(MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.PORTAL);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
// JWT signer
final Map<String, Object> claims = new HashMap<>();
claims.put(JWTHelper.Claims.ISSUER, environment.getProperty("jwt.issuer", JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER));
claims.put(JWTHelper.Claims.SUBJECT, user.getId());
claims.put(JWTHelper.Claims.PERMISSIONS, authorities);
claims.put(JWTHelper.Claims.EMAIL, user.getEmail());
claims.put(JWTHelper.Claims.FIRSTNAME, user.getFirstname());
claims.put(JWTHelper.Claims.LASTNAME, user.getLastname());
final JWTSigner.Options options = new JWTSigner.Options();
options.setExpirySeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER));
options.setIssuedAt(true);
options.setJwtId(true);
return Response.ok().entity(user).cookie(new NewCookie(HttpHeaders.AUTHORIZATION, "Bearer " + new JWTSigner(environment.getProperty("jwt.secret")).sign(claims, options), environment.getProperty("jwt.cookie-path", "/"), environment.getProperty("jwt.cookie-domain"), "", environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER), environment.getProperty("jwt.cookie-secure", Boolean.class, false), true)).build();
}
use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.
the class OAuth2AuthenticationResourceTest method verifyJwtToken.
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerifyException {
String cookieContent = response.getCookies().get(HttpHeaders.AUTHORIZATION).getValue();
assertThat(cookieContent, StringStartsWith.startsWith("Bearer "));
String jwt = cookieContent.substring(7);
JWTVerifier jwtVerifier = new JWTVerifier("myJWT4Gr4v1t33_S3cr3t");
Map<String, Object> mapJwt = jwtVerifier.verify(jwt);
assertEquals(mapJwt.get("sub"), "janedoe@example.com");
assertEquals(mapJwt.get("firstname"), "Jane");
assertEquals(mapJwt.get("iss"), "gravitee-management-auth");
assertEquals(mapJwt.get("sub"), "janedoe@example.com");
assertEquals(mapJwt.get("email"), "janedoe@example.com");
assertEquals(mapJwt.get("lastname"), "Doe");
}
Aggregations