0
votes

I have a Keycloak connector that allows me to retrieve the user's username through SSO. I want to use this username to authenticate the user and to look up his authorities in a database and inject this user authority in spring security to be able to use its functionalities.

I've created a custom authenticationProvider with a custom UserDetailsService and the problem I keep facing is that I get redirected every time to spring security login page. I think when it sees that there is no authentication object in the request it does it by its own.

This is the code to retrieve the username. I feel like I have most of the pieces but I don't know how to inject it in spring security or at least all the ideas I had until now wouldn't work. This is why I hope to find someone who's an expert in Spring security who would point me in the right direction. Thanks in advance

KeycloakSecurityContext sc = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());
IDToken idToken=sc.getIdToken();
String userId=idToken.getPreferredUsername();
1
Set the log level to DEBUG and then try to log in. Take a look at the logs, you will find a line with the exact reason of why auth failed or why auth has to be retried. Also, paste those log entries here so we can take a look. You are probably not populating the security context correctly. - rodrigoap
show how you implement your the custom AuthenticationProvider - Ken Chan

1 Answers

0
votes

This is what i ended up doing, i created a CustomAuthenticationFilter extends GenericFilterBean that i placed in the filter chain through SecurityConfig extends WebSecurityConfigurerAdapter , inside this filter in the doFilter method i retrieve the username and create a UsernamePasswordAuthenticationToken that is then added to the SecurityContext from which i retrieve the username in a CustomAuthenticationProvider that creates the authentication by calling a database and retrieving the roles.