use of com.auth0.android.jwt.JWT in project gravitee-api-management by gravitee-io.
the class CurrentUserResource method login.
@POST
@Path("/login")
@ApiOperation(value = "Login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context final javax.ws.rs.core.HttpHeaders headers, @Context final HttpServletResponse servletResponse) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
// JWT signer
final Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
// We must also load permissions from repository for configured management or portal role
Set<RoleEntity> roles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getUsername());
if (!roles.isEmpty()) {
roles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
this.environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()).stream().flatMap(env -> membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, env.getId(), MembershipMemberType.USER, userDetails.getUsername()).stream()).filter(Objects::nonNull).forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
// JWT signer
Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
Date issueAt = new Date();
Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
final String token = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(userDetails.getUsername()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, userDetails.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setType(BEARER);
tokenEntity.setToken(token);
final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
servletResponse.addCookie(bearerCookie);
return ok(tokenEntity).build();
}
return ok().build();
}
use of com.auth0.android.jwt.JWT in project gravitee-api-management 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(GraviteeContext.getCurrentOrganization(), 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.android.jwt.JWT 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.android.jwt.JWT in project gravitee-api-management by gravitee-io.
the class AuthResource method login.
@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context final javax.ws.rs.core.HttpHeaders headers, @Context final HttpServletResponse servletResponse) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
// JWT signer
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
// We must also load permissions from repository for configured environment role
Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId());
if (!userRoles.isEmpty()) {
userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
Date issueAt = new Date();
Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
final String sign = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(userDetails.getUsername()).withClaim(Claims.PERMISSIONS, authorities).withClaim(Claims.EMAIL, userDetails.getEmail()).withClaim(Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final Token tokenEntity = new Token();
tokenEntity.setTokenType(TokenTypeEnum.BEARER);
tokenEntity.setToken(sign);
final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
servletResponse.addCookie(bearerCookie);
return ok(tokenEntity).build();
}
return ok().build();
}
use of com.auth0.android.jwt.JWT in project cx-flow by checkmarx-ltd.
the class GitHubAppAuthService method getJwt.
private String getJwt(String appId) {
// Check if current token is set and if it is verified
LocalDateTime currentDateTime = LocalDateTime.now(ZoneOffset.UTC);
if (this.jwt != null) {
DecodedJWT decodedJwt = JWT.decode(this.jwt);
Instant currentTime = currentDateTime.plusMinutes(1).toInstant(ZoneOffset.UTC);
if (currentTime.isBefore(decodedJwt.getExpiresAt().toInstant())) {
return this.jwt;
}
}
// If the jwt was null or expired, we hit this block to create new
// 10 minutes in future
LocalDateTime exp = currentDateTime.plusMinutes(10);
assert this.privateKey != null;
Algorithm algorithm = Algorithm.RSA256(null, this.privateKey);
// set the current token and return it
this.jwt = JWT.create().withIssuer(appId).withIssuedAt(Date.from(currentDateTime.toInstant(ZoneOffset.UTC))).withExpiresAt(Date.from(exp.toInstant(ZoneOffset.UTC))).sign(algorithm);
return this.jwt;
}
Aggregations