Spring Boot Authorization Server向外部服务发送请求以获取用户详细信息

时间:2017-08-23 19:42:47

标签: java spring spring-security authorization microservices

我收到了很多服务,我希望通过身份验证服务集中我的身份验证。现在我是Spring引导的noobie,我不知道如何才能实现这一目标。

我只是实现了Spring的常规安全性,它运行得很好,我只找到一些关于jdbcAuthenticationinMemoryAuthentication等的教程,但不是身份验证服务向另一个服务发送请求的身份验证。有没有人对此有所了解?

我的基于令牌的安全性 - > JWT

我认为我需要操纵AuthenticationManagerBuilder,因为它决定了用户名是否有效。

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}

我用Feign提出请求 - 这个代码可能是错误的位置

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

1 个答案:

答案 0 :(得分:1)

您可以这样配置:

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