首页 > 解决方案 > 如何在 Spring Boot Security 的另一个微服务中调用我的身份验证微服务

问题描述

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

标签: spring-bootauthenticationspring-securityrestful-authentication

解决方案


您可以使用自定义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. 将您的 bean 声明CustomRemoteAuthenticationProvider为 bean(您可以在 中执行此操作WebSecurityConfigurerAdapter),它将被自动拾取并添加到AuthenticationManager
@Bean
public CustomRemoteAuthenticationProvider customRemoteAuthenticationProvider() {
    return new CustomRemoteAuthenticationProvider();
}

注意:您可以通过@Component直接添加到CustomRemoteAuthenticationProvider. 此外,如果您想了解更多关于如何编写的想法,请查看 javadocAuthenticationProvider获取 s 列表。通常用于对数据库进行身份验证。AuthenticationProviderDaoAuthenticationProviderJdbcDaoImpl


推荐阅读