use of io.gravitee.rest.api.service.TokenService 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);
}
Aggregations