I have added a filter that reads cookies and stores a UserDetails
performs SecurityContextHolder.getContext().setAuthentication(ssoUserDetails)
. The details are for a user that exists in the database.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
HttpServletRequest httpRequest = asHttp(request);
CookieMap cookieMap = new CookieMap(httpRequest);
Optional<Cookie> cookie = Optional.fromNullable(cookieMap.get(getCookieName()));
if (cookie.isPresent()) {
CookieInstanceAuthentication cookieAuthentication = CookieInstanceAuthentication.builder()
.cookie(cookie)
.build();
Optional<Authentication> resultOfAuthentication = tryToAuthenticate(cookieAuthentication);
if (resultOfAuthentication.isPresent() && resultOfAuthentication.get().isAuthenticated()) {
securityContext.setAuthentication(resultOfAuthentication.get());
authentication = securityContext.getAuthentication();
logger.debug("CommuntityUser successfully authenticated via cookies. " + authentication.getPrincipal());
}
}
}
chain.doFilter(request, response);
}
I have debugged and logged the information to ensure that part is working correctly.
However, when I load any page or hit an api endpoint (without providing OAuth2 credentials/tokens) the user is not authenticated. I tracked this down to the OAuth2AuthenticationProcessingFilter
writing over my authentication.
What is the suggested method for adding additional authentication mechanisms?