我正在尝试使用Spring安全性对包含SSL证书的请求进行身份验证。
我正在寻找可以实现它的流程
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CertificateAuthenticationProvider certificateAuthenticationProvider;
@Autowired
private CustomX509AuthenticationFilter customX509AuthenticationFilter;
@Autowired
public SecurityConfig(CertificateAuthenticationProvider certificateAuthenticationProvider) {
this.certificateAuthenticationProvider = certificateAuthenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.x509().x509AuthenticationFilter(MyX509AuthenticationFilter)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.authorizeRequests().antMatchers("/").denyAll().anyRequest().authenticated();
}
@Bean
@Override
protected AuthenticationManager authenticationManager() {
try {
return super.authenticationManager();
} catch (Exception ex) {
throw new IllegalStateException("Failed to extract AuthenticationManager.", ex);
}
}
}
AuthenticationFilter类
@Component
public class MyX509AuthenticationFilter extends X509AuthenticationFilter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Authentication unauthenticatedToken = getUserCredentialsFromRequest(request);
Authentication authenticatedToken = authenticationManager.authenticate(unauthenticatedToken);
if(authenticatedToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticatedToken);
chain.doFilter(request, response);
}
else {
throw new BadCredentialsException("Invalid Credentials");
}
}
private Authentication getUserCredentialsFromRequest(ServletRequest request) {
// logic to retrieve user credentials from request and create initial
// Authentication
return ...;
}
}
用于提供身份验证的AuthenticationProvider类
@Component
public class CertificateAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// TODO Auto-generated method stub
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
return new MyCertificateDetails("xc","cv");
}
}
我需要认证证书的地方。在这里,需要MyX509AuthenticationFilter吗?