use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class OAuth2AuthenticationResource method processUser.
private Response processUser(final SocialIdentityProviderEntity socialProvider, final HttpServletResponse servletResponse, final String userInfo, final String state, final String accessToken, final String idToken) {
UserEntity user = userService.createOrUpdateUserFromSocialIdentityProvider(socialProvider, userInfo);
String userId = user.getId();
final Set<GrantedAuthority> authorities = authoritiesProvider.retrieveAuthorities(user.getId());
// set user to Authentication Context
UserDetails userDetails = new UserDetails(userId, "", authorities);
userDetails.setEmail(user.getEmail());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
return connectUser(userId, state, servletResponse, accessToken, idToken);
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class AbstractAuthenticationResource method connectUserInternal.
protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
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> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId());
if (!userRoles.isEmpty()) {
userRoles.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(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setType(BEARER);
tokenEntity.setToken(token);
if (idToken != null) {
tokenEntity.setAccessToken(accessToken);
tokenEntity.setIdToken(idToken);
}
if (state != null && !state.isEmpty()) {
tokenEntity.setState(state);
}
final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
servletResponse.addCookie(bearerCookie);
return Response.ok(tokenEntity).build();
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class OAuth2AuthenticationResource method processUser.
private Response processUser(final SocialIdentityProviderEntity socialProvider, final HttpServletResponse servletResponse, final String userInfo, final String state, final String accessToken, final String idToken) {
UserEntity user = userService.createOrUpdateUserFromSocialIdentityProvider(socialProvider, userInfo);
final Set<GrantedAuthority> authorities = authoritiesProvider.retrieveAuthorities(user.getId());
// set user to Authentication Context
UserDetails userDetails = new UserDetails(user.getId(), "", authorities);
userDetails.setEmail(user.getEmail());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
return connectUser(user.getId(), state, servletResponse, accessToken, idToken);
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails 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 io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class AuthenticationSuccessListener method onApplicationEvent.
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
final UserDetails details = (UserDetails) event.getAuthentication().getPrincipal();
try {
UserEntity registeredUser = userService.findBySource(details.getSource(), details.getSourceId(), false);
updateRegisteredUser(registeredUser, details);
// Principal username is the technical identifier of the user
// Dirty hack because spring security is requiring a username...
details.setUsername(registeredUser.getId());
// Allows to override email of in memory users
if ("memory".equals(details.getSource()) && registeredUser.getEmail() != null) {
details.setEmail(registeredUser.getEmail());
SecurityContextHolder.getContext().setAuthentication(event.getAuthentication());
}
} catch (UserNotFoundException unfe) {
final NewExternalUserEntity newUser = new NewExternalUserEntity();
newUser.setSource(details.getSource());
newUser.setSourceId(details.getSourceId());
newUser.setFirstname(details.getFirstname());
newUser.setLastname(details.getLastname());
newUser.setEmail(details.getEmail());
byte[] pictureData = details.getPicture();
if (pictureData != null && pictureData.length > 0) {
String picture = computePicture(pictureData);
newUser.setPicture(picture);
}
boolean addDefaultRole = false;
if (event.getAuthentication().getAuthorities() == null || event.getAuthentication().getAuthorities().isEmpty()) {
addDefaultRole = true;
}
UserEntity createdUser = userService.create(newUser, addDefaultRole);
// Principal username is the technical identifier of the user
details.setUsername(createdUser.getId());
if (!addDefaultRole) {
addRole(RoleScope.ENVIRONMENT, createdUser.getId(), event.getAuthentication().getAuthorities());
addRole(RoleScope.ORGANIZATION, createdUser.getId(), event.getAuthentication().getAuthorities());
}
}
userService.connect(details.getUsername());
}
Aggregations