use of io.gravitee.rest.api.model.UserEntity 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.model.UserEntity 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.model.UserEntity 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.model.UserEntity in project gravitee-management-rest-api by gravitee-io.
the class TokenAuthenticationFilterTest method shouldGenerateAuthorities.
@Test
public void shouldGenerateAuthorities() throws Exception {
final String USER_ID = "userid1";
final String TOKEN = "b4c6102e-6c95-464f-8610-2e6c95064f02";
final String BEARER = "Bearer " + TOKEN;
TokenAuthenticationFilter filter = new TokenAuthenticationFilter("JWT_SECRET_TOEKN_TEST", cookieGenerator, userService, tokenService, authoritiesProvider);
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(BEARER);
final Token token = mock(Token.class);
when(token.getReferenceId()).thenReturn(USER_ID);
when(tokenService.findByToken(TOKEN)).thenReturn(token);
UserEntity user = mock(UserEntity.class);
when(user.getId()).thenReturn(USER_ID);
when(userService.findById(USER_ID)).thenReturn(user);
filter.doFilter(request, response, filterChain);
verify(authoritiesProvider).retrieveAuthorities(USER_ID);
}
use of io.gravitee.rest.api.model.UserEntity in project gravitee-management-rest-api by gravitee-io.
the class MembershipCommandHandler method handle.
@Override
public Single<MembershipReply> handle(MembershipCommand command) {
MembershipPayload membershipPayload = command.getPayload();
GraviteeContext.setCurrentOrganization(membershipPayload.getOrganizationId());
try {
RoleScope roleScope;
MembershipReferenceType membershipReferenceType;
try {
roleScope = RoleScope.valueOf(membershipPayload.getReferenceType());
membershipReferenceType = MembershipReferenceType.valueOf(membershipPayload.getReferenceType());
} catch (Exception e) {
logger.error("Invalid referenceType [{}].", membershipPayload.getReferenceType());
return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
}
final UserEntity userEntity = userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false);
final RoleEntity roleEntity = findRole(roleScope, membershipPayload.getRole());
final MembershipService.MembershipReference membershipReference = new MembershipService.MembershipReference(membershipReferenceType, membershipPayload.getReferenceId());
final MembershipService.MembershipMember membershipMember = new MembershipService.MembershipMember(userEntity.getId(), null, MembershipMemberType.USER);
final MembershipService.MembershipRole membershipRole = new MembershipService.MembershipRole(roleEntity.getScope(), roleEntity.getName());
membershipService.updateRolesToMemberOnReference(membershipReference, membershipMember, Collections.singletonList(membershipRole), COCKPIT_SOURCE, false);
logger.info("Role [{}] assigned on {} [{}] for user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), userEntity.getId(), membershipPayload.getOrganizationId());
return Single.just(new MembershipReply(command.getId(), CommandStatus.SUCCEEDED));
} catch (Exception e) {
logger.error("Error occurred when trying to assign role [{}] on {} [{}] for cockpit user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), membershipPayload.getUserId(), membershipPayload.getOrganizationId(), e);
return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
} finally {
GraviteeContext.cleanContext();
}
}
Aggregations