From 7e01e2ddac4e53077f43210a506eac3f91bd8259 Mon Sep 17 00:00:00 2001 From: Michael Sprauer Date: Tue, 3 Sep 2019 12:09:37 +0200 Subject: [PATCH] only set authentication if not yet authenticated Signed-off-by: Michael Sprauer --- .../active_directory/HttpHeaderFilter.java | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/main/java/hudson/plugins/active_directory/HttpHeaderFilter.java b/src/main/java/hudson/plugins/active_directory/HttpHeaderFilter.java index e8ebc1ea..53eb49fd 100644 --- a/src/main/java/hudson/plugins/active_directory/HttpHeaderFilter.java +++ b/src/main/java/hudson/plugins/active_directory/HttpHeaderFilter.java @@ -8,6 +8,7 @@ import org.acegisecurity.GrantedAuthority; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; +import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UsernameNotFoundException; @@ -30,23 +31,27 @@ public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; - Authentication auth = Jenkins.ANONYMOUS; - String authenticatedUserFromApiToken = getUserFromAuthorizationHeader(request); - String userName = authenticatedUserFromApiToken == null ? getUserFromReverseProxyHeader(request) : authenticatedUserFromApiToken; - if (userName != null) { - try { - UserDetails userDetails = activeDirectorySecurityRealm.getAuthenticationProvider().loadUserByUsername(userName); + if (SecurityContextHolder.getContext().getAuthentication() == null || + SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken) { + Authentication auth = Jenkins.ANONYMOUS; + String authenticatedUserFromApiToken = getUserFromAuthorizationHeader(request); - GrantedAuthority[] authorities = userDetails.getAuthorities(); + String userName = authenticatedUserFromApiToken == null ? getUserFromReverseProxyHeader(request) : authenticatedUserFromApiToken; + if (userName != null) { + try { + UserDetails userDetails = activeDirectorySecurityRealm.getAuthenticationProvider().loadUserByUsername(userName); - auth = new UsernamePasswordAuthenticationToken(userName, "", authorities); - } catch (UsernameNotFoundException e) { - LOGGER.log(Level.FINE, "User from HTTP Header {0} not found in LDAP", userName); + GrantedAuthority[] authorities = userDetails.getAuthorities(); + + auth = new UsernamePasswordAuthenticationToken(userName, "", authorities); + } catch (UsernameNotFoundException e) { + LOGGER.log(Level.FINE, "User from HTTP Header {0} not found in LDAP", userName); + } } - } - SecurityContextHolder.getContext().setAuthentication(auth); + SecurityContextHolder.getContext().setAuthentication(auth); + } chain.doFilter(request, response); }