【问题标题】:How to call my authentication microservice in another microservice in spring boot security如何在 Spring Boot Security 的另一个微服务中调用我的身份验证微服务
【发布时间】:2020-06-16 22:55:40
【问题描述】:

我已经使用 Spring Security 实现了一个身份验证服务,它可以访问存储用户数据的数据库。现在我想实现另一个服务(打开一个全新的项目),我只指定我的身份验证服务的 url。我使用.loginProcessingUrl() 并在spring security 配置中更改了登录页面,但这不起作用。如何使新服务使用我的身份验证服务进行身份验证?

【问题讨论】:

  • 你在使用 Spring Boot 吗?
  • 是的,问题在于如何调用已经实现的身份验证服务并避免使用spring security提供的默认服务
  • 您是否尝试过将执行此操作的自定义 AuthenticationProvider 添加到 AuthenticationManager?
  • 不,我没有,我只是更改了登录页面的 url 和 loginProcessUrl
  • 您在配置中的某处使用 formLogin().loginProcessingUrl()?我问是因为有很多选项可以实现这一点(比如将过滤器添加到过滤器链中)。这取决于您需要什么的复杂性。例如,新服务是否会通过身份验证服务对自己进行身份验证?身份验证服务如何知道它向您的服务提供信息而不是其他人的信息?

标签: spring-boot authentication spring-security restful-authentication


【解决方案1】:

您可以使用自定义AuthenticationProvider 为您进行身份验证。

这是一个简单的例子:

  1. 创建一个调用您的身份验证服务的CustomRemoteAuthenticationProvider
public class CustomRemoteAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) 
               throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // call your authentication service
        // ... and return a UsernamePasswordAuthenticationToken

    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
  1. 将您的CustomRemoteAuthenticationProvider 声明为一个bean(您可以在WebSecurityConfigurerAdapter 中执行此操作),它将被自动拾取并添加到AuthenticationManager
@Bean
public CustomRemoteAuthenticationProvider customRemoteAuthenticationProvider() {
    return new CustomRemoteAuthenticationProvider();
}

注意:您可以通过将@Component 直接添加到CustomRemoteAuthenticationProvider 来一步完成所有这些操作。此外,check out the javadoc 用于 AuthenticationProvider 以获取 AuthenticationProviders 的列表,如果您想了解更多关于如何编写的想法。 DaoAuthenticationProvider 通常与 JdbcDaoImpl 一起用于对数据库进行身份验证。

【讨论】:

  • UsernamePasswordAuthenticationFilter 是调用您的 AuthenticationProvider 的过滤器,因此如果您想确切知道会发生什么,可以查看它
  • 这个听起来很不错但是如何调用认证服务
  • 让我使用 restTemplate 来传递 url
  • 是的,你可以这样做,或者 HttpClient
  • 我肯定会尝试这个,我会尽快告诉你谢谢
猜你喜欢
  • 1970-01-01
  • 2018-07-17
  • 2020-04-27
  • 2020-09-25
  • 2021-08-13
  • 2018-03-04
  • 2022-01-15
  • 2018-08-21
  • 1970-01-01
相关资源
最近更新 更多