use of io.gravitee.repository.management.model.Token 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.repository.management.model.Token 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.repository.management.model.Token in project gravitee-management-rest-api by gravitee-io.
the class TokenServiceImpl method revoke.
@Override
public void revoke(String tokenId) {
try {
Optional<Token> tokenOptional = tokenRepository.findById(tokenId);
if (tokenOptional.isPresent()) {
tokenRepository.delete(tokenId);
auditService.createEnvironmentAuditLog(Collections.singletonMap(TOKEN, tokenId), TOKEN_DELETED, new Date(), null, tokenOptional.get());
}
} catch (TechnicalException ex) {
final String error = "An error occurs while trying to delete token " + tokenId;
LOGGER.error(error, ex);
throw new TechnicalManagementException(error, ex);
}
}
use of io.gravitee.repository.management.model.Token in project gravitee-management-rest-api by gravitee-io.
the class TokenServiceImpl method findByToken.
@Override
public Token findByToken(String token) {
try {
LOGGER.debug("Find token entity by token value");
final Optional<Token> optionalToken = tokenRepository.findAll().stream().filter(t -> passwordEncoder.matches(token, t.getToken())).findAny();
if (optionalToken.isPresent()) {
final Token t = optionalToken.get();
t.setLastUseAt(new Date());
return tokenRepository.update(t);
}
throw new IllegalStateException("Token not found");
} catch (TechnicalException ex) {
final String error = "An error occurs while trying to find token entity for a given token value";
LOGGER.error(error, ex);
throw new TechnicalManagementException(error, ex);
}
}
use of io.gravitee.repository.management.model.Token in project gravitee-management-rest-api by gravitee-io.
the class TokenServiceImpl method convert.
private Token convert(final NewTokenEntity tokenEntity, final TokenReferenceType referenceType, final String referenceId, final String encodedToken) {
final Token token = new Token();
token.setId(UUID.toString(UUID.random()));
token.setToken(encodedToken);
token.setName(tokenEntity.getName());
token.setCreatedAt(new Date());
token.setReferenceType(referenceType.name());
token.setReferenceId(referenceId);
return token;
}
Aggregations