use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class InMemoryGraviteeUserDetailsManager method loadUserByUsername.
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails user = users.get(username.toLowerCase());
if (user == null) {
throw new UsernameNotFoundException(username);
}
// return a copy of the user 'cause spring will erase credentials in the security process
UserDetails userDetails = new UserDetails(user.getUsername(), user.getPassword(), user.getEmail(), user.getAuthorities());
userDetails.setSource(InMemoryIdentityProvider.PROVIDER_TYPE);
userDetails.setSourceId(user.getUsername());
userDetails.setFirstname(user.getFirstname());
userDetails.setLastname(user.getLastname());
return userDetails;
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class InMemoryGraviteeUserDetailsManager method convert.
private UserDetails convert(org.springframework.security.core.userdetails.UserDetails user) {
if (user instanceof UserDetails) {
return (UserDetails) user;
}
UserDetails userDetails = new UserDetails(user.getUsername(), user.getPassword(), user.getAuthorities());
userDetails.setSource(InMemoryIdentityProvider.PROVIDER_TYPE);
userDetails.setSourceId(user.getUsername());
if (user instanceof io.gravitee.rest.api.idp.api.authentication.UserDetails) {
userDetails.setFirstname(((io.gravitee.rest.api.idp.api.authentication.UserDetails) user).getFirstname());
userDetails.setLastname(((io.gravitee.rest.api.idp.api.authentication.UserDetails) user).getLastname());
}
return userDetails;
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class AuditServiceImpl method createAuditLog.
@Async
@Override
public void createAuditLog(Audit.AuditReferenceType referenceType, String referenceId, Map<Audit.AuditProperties, String> properties, Audit.AuditEvent event, Date createdAt, Object oldValue, Object newValue) {
Audit audit = new Audit();
audit.setId(UuidString.generateRandom());
audit.setCreatedAt(createdAt == null ? new Date() : createdAt);
final UserDetails authenticatedUser = getAuthenticatedUser();
final String user;
if (authenticatedUser != null && "token".equals(authenticatedUser.getSource())) {
user = userService.findById(authenticatedUser.getUsername()).getDisplayName() + " - (using token \"" + authenticatedUser.getSourceId() + "\")";
} else {
user = getAuthenticatedUsernameOrSystem();
}
audit.setUser(user);
if (properties != null) {
Map<String, String> stringStringMap = new HashMap<>(properties.size());
properties.forEach((auditProperties, s) -> stringStringMap.put(auditProperties.name(), s));
audit.setProperties(stringStringMap);
}
audit.setReferenceType(referenceType);
audit.setReferenceId(referenceId);
audit.setEvent(event.name());
ObjectNode oldNode = oldValue == null ? mapper.createObjectNode() : mapper.convertValue(oldValue, ObjectNode.class).remove(Arrays.asList("updatedAt", "createdAt"));
ObjectNode newNode = newValue == null ? mapper.createObjectNode() : mapper.convertValue(newValue, ObjectNode.class).remove(Arrays.asList("updatedAt", "createdAt"));
audit.setPatch(JsonDiff.asJson(oldNode, newNode).toString());
try {
auditRepository.create(audit);
} catch (TechnicalException e) {
LOGGER.error("Error occurs during the creation of an Audit Log {}.", e);
}
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class AuthResourceTest method shouldLogin.
@Test
public void shouldLogin() {
final UserDetails userDetails = new UserDetails(USER_NAME, "PASSWORD", Collections.emptyList());
final Authentication authentication = mock(Authentication.class);
when(authentication.getPrincipal()).thenReturn(userDetails);
final SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
SecurityContextHolder.setContext(securityContext);
Cookie bearer = new Cookie("FOO", "BAR");
doReturn(bearer).when(cookieGenerator).generate(any());
final Response response = target().path("login").request().post(null);
assertEquals(HttpStatusCode.OK_200, response.getStatus());
Token token = response.readEntity(Token.class);
assertNotNull(token);
assertNotNull(token.getToken());
assertNotEquals("", token.getToken());
assertEquals(TokenTypeEnum.BEARER, token.getTokenType());
// APIPortal: can't test Cookie, since servletResponse is mocked
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api 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();
}
Aggregations