首页 > 解决方案 > 在基于证书的客户端的情况下调用 AuthenticationManager

问题描述

使用基于证书的客户端身份验证时,spring 会调用哪个 AuthenticationManager?目前我正在使用 PamAuthentication,我需要使用基于证书的身份验证。我看到 org.springframework.security.core.userdetails.UserDetailsS​​ervice 不再被调用。在基于证书的身份验证的情况下调用哪个实现?

标签: springoauth-2.0

解决方案


当使用基于证书的身份验证时,AbstractPreAuthenticatedProcessingFilter将负责对客户端进行身份验证。首先,过滤器通过X509AuthenticationFilter. 之后,使用证书 CN 作为主体,使用证书 DN 作为凭证​​来创建身份验证令牌。将AuthenticationManager执行该令牌身份验证的实现是PreAuthenticatedAuthenticationProvider,它将使用您的实现UserDetailsService来对客户端进行身份验证。

您可以通过将其添加到 HttpConfigurer 来启用证书身份验证,并配置您自己的UserDetailsService.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .x509()
        .subjectPrincipalRegex("CN=(.*?)")
        .userDetailsService(userDetailsService());
}

@Bean
public UserDetailsService userDetailsService() {
    return new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            Optional<User> user = userRepository.findByUsername(username);
            if(user.isPresent()){
                return new User(username, userCredentials, new Role("ROLE_USER"));
            }
            throw new UsernameNotFoundException("User" + username + "does not exist");
        }
    };
}

这里有一个 x509 证书身份验证的示例。


推荐阅读