Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Authorization Server send request to external service to get user details

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()));
}
like image 239
Guchelkaben Avatar asked Aug 23 '17 19:08

Guchelkaben


1 Answers

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");
      }
    };
 }
like image 177
alayor Avatar answered Oct 26 '22 22:10

alayor