Skip to content

Commit

Permalink
[OAuth2] Minor refactoring of Auth Filters
Browse files Browse the repository at this point in the history
  • Loading branch information
Alessio Fabiani committed Feb 9, 2018
1 parent 8a295e0 commit 3c9eda7
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 79 deletions.
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
*/ */
package org.geoserver.security.oauth2; package org.geoserver.security.oauth2;


import java.util.logging.Level;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.geoserver.security.config.SecurityNamedServiceConfig; import org.geoserver.security.config.SecurityNamedServiceConfig;
import org.springframework.security.oauth2.client.OAuth2RestOperations; import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices; import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
Expand All @@ -21,4 +26,31 @@ public GeoNodeOAuthAuthenticationFilter(SecurityNamedServiceConfig config,
super(config, tokenServices, oauth2SecurityConfiguration, oauth2RestTemplate); super(config, tokenServices, oauth2SecurityConfiguration, oauth2RestTemplate);
} }


@Override
protected String getCustomSessionCookieValue(HttpServletRequest request) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Inspecting the http request looking for the Custom Session ID.");
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found " + cookies.length + " cookies!");
}
for (Cookie c : cookies) {
if (c.getName().equalsIgnoreCase(SESSION_COOKIE_NAME)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found Custom Session cookie: " + c.getValue());
}
return c.getValue();
}
}
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found no cookies!");
}
}

return null;
}

} }
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
*/ */
package org.geoserver.security.oauth2; package org.geoserver.security.oauth2;


import java.util.logging.Level;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.geoserver.security.config.SecurityNamedServiceConfig; import org.geoserver.security.config.SecurityNamedServiceConfig;
import org.springframework.security.oauth2.client.OAuth2RestOperations; import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices; import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
Expand All @@ -21,4 +26,31 @@ public GitHubOAuthAuthenticationFilter(SecurityNamedServiceConfig config,
super(config, tokenServices, oauth2SecurityConfiguration, oauth2RestTemplate); super(config, tokenServices, oauth2SecurityConfiguration, oauth2RestTemplate);
} }


@Override
protected String getCustomSessionCookieValue(HttpServletRequest request) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Inspecting the http request looking for the JSession ID.");
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found " + cookies.length + " cookies!");
}
for (Cookie c : cookies) {
if (c.getName().equalsIgnoreCase(SESSION_COOKIE_NAME)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found Custom Session cookie: " + c.getValue());
}
return c.getValue();
}
}
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found no cookies!");
}
}

return null;
}

} }
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
*/ */
package org.geoserver.security.oauth2; package org.geoserver.security.oauth2;


import java.util.logging.Level;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.geoserver.security.config.SecurityNamedServiceConfig; import org.geoserver.security.config.SecurityNamedServiceConfig;
import org.springframework.security.oauth2.client.OAuth2RestOperations; import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices; import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
Expand All @@ -21,4 +26,31 @@ public GoogleOAuthAuthenticationFilter(SecurityNamedServiceConfig config,
super(config, tokenServices, oauth2SecurityConfiguration, oauth2RestTemplate); super(config, tokenServices, oauth2SecurityConfiguration, oauth2RestTemplate);
} }


@Override
protected String getCustomSessionCookieValue(HttpServletRequest request) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Inspecting the http request looking for the JSession ID.");
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found " + cookies.length + " cookies!");
}
for (Cookie c : cookies) {
if (c.getName().equalsIgnoreCase(SESSION_COOKIE_NAME)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found Custom Session cookie: " + c.getValue());
}
return c.getValue();
}
}
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found no cookies!");
}
}

return null;
}

} }
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.geoserver.security.GeoServerUserGroupService; import org.geoserver.security.GeoServerUserGroupService;
import org.geoserver.security.config.PreAuthenticatedUserNameFilterConfig.PreAuthenticatedUserNameRoleSource; import org.geoserver.security.config.PreAuthenticatedUserNameFilterConfig.PreAuthenticatedUserNameRoleSource;
import org.geoserver.security.config.SecurityNamedServiceConfig; import org.geoserver.security.config.SecurityNamedServiceConfig;
import org.geoserver.security.filter.AuthenticationCachingFilter;
import org.geoserver.security.filter.GeoServerAuthenticationFilter; import org.geoserver.security.filter.GeoServerAuthenticationFilter;
import org.geoserver.security.filter.GeoServerLogoutFilter; import org.geoserver.security.filter.GeoServerLogoutFilter;
import org.geoserver.security.filter.GeoServerPreAuthenticatedUserNameFilter; import org.geoserver.security.filter.GeoServerPreAuthenticatedUserNameFilter;
Expand Down Expand Up @@ -60,7 +59,7 @@ public abstract class GeoServerOAuthAuthenticationFilter
extends GeoServerPreAuthenticatedUserNameFilter extends GeoServerPreAuthenticatedUserNameFilter
implements GeoServerAuthenticationFilter, LogoutHandler { implements GeoServerAuthenticationFilter, LogoutHandler {


static final String CUSTOM_SESSION_COOKIE_NAME = "sessionid"; public static final String SESSION_COOKIE_NAME = "sessionid";


OAuth2FilterConfig filterConfig; OAuth2FilterConfig filterConfig;


Expand Down Expand Up @@ -102,11 +101,8 @@ public AuthenticationEntryPoint getAuthenticationEntryPoint() {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { throws IOException, ServletException {


String cacheKey = authenticateFromCache(this, (HttpServletRequest) request,
(HttpServletResponse) response);

// Search for an access_token on the request (simulating SSO) // Search for an access_token on the request (simulating SSO)
String accessToken = request.getParameter("access_token"); final String accessToken = request.getParameter("access_token");


OAuth2AccessToken token = restTemplate.getOAuth2ClientContext().getAccessToken(); OAuth2AccessToken token = restTemplate.getOAuth2ClientContext().getAccessToken();


Expand All @@ -115,15 +111,14 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
} }


HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;


/* /*
* This cookie works only locally, when accessing the GeoServer GUI and on the same domain. For remote access you need to logout from the * This cookie works only locally, when accessing the GeoServer GUI and on the same domain. For remote access you need to logout from the
* GeoServer GUI. * GeoServer GUI.
*/ */
final String customSessionCookie = getCustomSessionCookieValue(httpRequest, httpResponse); final String customSessionCookie = getCustomSessionCookieValue(httpRequest);


final Authentication authentication = SecurityContextHolder.getContext() Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication(); .getAuthentication();
final Collection<? extends GrantedAuthority> authorities = (authentication != null final Collection<? extends GrantedAuthority> authorities = (authentication != null
? authentication.getAuthorities() ? authentication.getAuthorities()
Expand All @@ -148,92 +143,42 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
httpRequest.getSession(false).invalidate(); httpRequest.getSession(false).invalidate();
try { try {
httpRequest.logout(); httpRequest.logout();
authentication = null;
} catch (ServletException e) { } catch (ServletException e) {
LOGGER.fine(e.getLocalizedMessage()); LOGGER.fine(e.getLocalizedMessage());
} }
LOGGER.fine("Cleaned out Session Access Token Request!"); LOGGER.fine("Cleaned out Session Access Token Request!");
} }
} }


if ((authentication == null && accessToken != null) || authentication == null || (authentication != null if ((authentication == null && accessToken != null) || authentication == null
&& authorities.size() == 1 && authorities.contains(GeoServerRole.ANONYMOUS_ROLE))) { || (authentication != null && authorities.size() == 1
&& authorities.contains(GeoServerRole.ANONYMOUS_ROLE))) {


doAuthenticate((HttpServletRequest) request, (HttpServletResponse) response); doAuthenticate((HttpServletRequest) request, (HttpServletResponse) response);


Authentication postAuthentication = authentication; Authentication postAuthentication = authentication;
if (postAuthentication != null && cacheKey != null) { if (postAuthentication != null) {
if (cacheAuthentication(postAuthentication, (HttpServletRequest) request)) { if (cacheAuthentication(postAuthentication, (HttpServletRequest) request)) {
getSecurityManager().getAuthenticationCache().put(getName(), cacheKey, getSecurityManager().getAuthenticationCache().put(getName(),
postAuthentication); getCacheKey((HttpServletRequest) request), postAuthentication);
} }
} }
} }

chain.doFilter(request, response);
}

protected String authenticateFromCache(AuthenticationCachingFilter filter,
HttpServletRequest request, HttpServletResponse response) {

Authentication authFromCache = null;
String cacheKey = null;
if (SecurityContextHolder.getContext().getAuthentication() == null) {
cacheKey = getCacheKey(request, response);
if (cacheKey != null) {
authFromCache = getSecurityManager().getAuthenticationCache().get(getName(),
cacheKey);
if (authFromCache != null)
SecurityContextHolder.getContext().setAuthentication(authFromCache);
else
return cacheKey;
}


} chain.doFilter(request, response);
return null;
} }


protected String getCacheKey(HttpServletRequest request, HttpServletResponse response) { /**

* The cache key is the authentication key (global identifier)
if (request.getSession(false) != null) // no caching if there is an HTTP session */
return null; @Override

public String getCacheKey(HttpServletRequest request) {
String retval; final String access_token = request.getParameter("access_token");
try { return access_token != null ? access_token : getCustomSessionCookieValue(request);
retval = getPreAuthenticatedPrincipal(request, response);
} catch (Exception e) {
return null;
}

if (GeoServerUser.ROOT_USERNAME.equals(retval))
return null;
return retval;
} }


private String getCustomSessionCookieValue(HttpServletRequest request, HttpServletResponse response) { protected abstract String getCustomSessionCookieValue(HttpServletRequest request);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Inspecting the http request looking for the Custom Session ID.");
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found " + cookies.length + " cookies!");
}
for (Cookie c : cookies) {
if (c.getName().toLowerCase().contains(CUSTOM_SESSION_COOKIE_NAME)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found Custom Session cookie: " + c.getValue());
}
return c.getValue();
}
}
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Found no cookies!");
}
}

return null;
}


@Override @Override
public void logout(HttpServletRequest request, HttpServletResponse response, public void logout(HttpServletRequest request, HttpServletResponse response,
Expand Down Expand Up @@ -307,7 +252,8 @@ protected void doAuthenticate(HttpServletRequest request, HttpServletResponse re
} else { } else {
if (GeoServerUser.ROOT_USERNAME.equals(principal)) { if (GeoServerUser.ROOT_USERNAME.equals(principal)) {
result = new PreAuthenticatedAuthenticationToken(principal, null, result = new PreAuthenticatedAuthenticationToken(principal, null,
Arrays.asList(GeoServerRole.ADMIN_ROLE, GeoServerRole.GROUP_ADMIN_ROLE, GeoServerRole.AUTHENTICATED_ROLE)); Arrays.asList(GeoServerRole.ADMIN_ROLE, GeoServerRole.GROUP_ADMIN_ROLE,
GeoServerRole.AUTHENTICATED_ROLE));
} else { } else {
Collection<GeoServerRole> roles = null; Collection<GeoServerRole> roles = null;
try { try {
Expand All @@ -317,8 +263,9 @@ protected void doAuthenticate(HttpServletRequest request, HttpServletResponse re
} }
if (roles.contains(GeoServerRole.AUTHENTICATED_ROLE) == false) if (roles.contains(GeoServerRole.AUTHENTICATED_ROLE) == false)
roles.add(GeoServerRole.AUTHENTICATED_ROLE); roles.add(GeoServerRole.AUTHENTICATED_ROLE);


RoleCalculator calc = new RoleCalculator(getSecurityManager().getActiveRoleService()); RoleCalculator calc = new RoleCalculator(
getSecurityManager().getActiveRoleService());
if (calc != null) { if (calc != null) {
try { try {
roles.addAll(calc.calculateRoles(principal)); roles.addAll(calc.calculateRoles(principal));
Expand All @@ -328,7 +275,7 @@ protected void doAuthenticate(HttpServletRequest request, HttpServletResponse re
e.getCause()); e.getCause());
} }
} }

result = new PreAuthenticatedAuthenticationToken(principal, null, roles); result = new PreAuthenticatedAuthenticationToken(principal, null, roles);


} }
Expand Down

0 comments on commit 3c9eda7

Please sign in to comment.