Skip to content

Commit

Permalink
only set authentication if not yet authenticated
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Sprauer <[email protected]>
  • Loading branch information
MichaelSp committed Sep 3, 2019
1 parent ec841ef commit 7e01e2d
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/main/java/hudson/plugins/active_directory/HttpHeaderFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
}

Expand Down

0 comments on commit 7e01e2d

Please sign in to comment.