I got a lot of services and I want to centralize my authentication with an authentication-service. Now I am a noobie at Spring boot and I have no clue how do I make this possible.
I just implement the normal security from Spring and it works perfectly and I only find some tutorials about jdbcAuthentication
, inMemoryAuthentication
, etc but not an authentication where the authentication-service send a request to another service. Does anyone get a clue about this?
My security based on tokens -> JWT
I think I need to manipulate the AuthenticationManagerBuilder
because it decides whether a username is valid or not.
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}
and I make my request with Feign - maybe the wrong location for this code
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
AccountCredentials credentials = new ObjectMapper()
.readValue(req.getInputStream(), AccountCredentials.class);
UserRequest userRequest = Feign.builder()
.decoder(new GsonDecoder())
.target(UserRequest.class,"http://localhost:7998/api/user-service/user/" + credentials.getUsername());
return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(credentials.getUsername(),credentials.getPassword(),emptyList()));
}
You can configure it this way:
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(getUserDetailsService());
}
@Bean
UserDetailsService getUserDetailsService() {
return username ->
{
JSONObject user = callUserService(username); //Here you send the UserRequest
if(user.has("email")) {
return new User(
user.getString("email"),
user.getString("password"),
true, true, true, true,
Collections.emptyList());
} else {
throw new BadCredentialsException("BadCredentialsException");
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With