我对Java Spring Boot的世界还很陌生,对正在从事的项目之一感到有些困惑。该项目需要使用两种身份验证方法,并且我只需要对某些请求使用x509。
基本上,应用程序现在使用的是使用令牌的身份验证,但是可以说我使用的是基本身份验证以简化过程。
因此,我建立了一个使用基本身份验证的基本测试应用程序。我有一个简单的控制器,有两种方法。
@GetMapping("/test")
private String test() {
return "we use basic auth only";
}
@GetMapping("/certiTest")
private String testCert() {
return "we use certificate auth on this method";
}
我希望第一种方法仅要求基本身份验证,第二种要求用户也具有正确的证书才能访问该方法。
问题是我无法同时使用一个或多个而遇到麻烦。我已经尝试了一些在线阅读的内容,现在我的WebSecurityConfig类看起来像这样
@Configuration
@EnableWebSecurity
public class WebSecurityConfig{
public static class BasicAuthConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and().httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authentication)
throws Exception
{
authentication.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("user"))
.authorities("ROLE_USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Configuration
@Order(2)
public static class X509SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/user/certiTest").authorizeRequests()
.anyRequest().authenticated().and()
.x509()
.subjectPrincipalRegex("CN=(.*?)(?:,|$)")
.userDetailsService(userDetailsService());
http.headers().httpStrictTransportSecurity()
.maxAgeInSeconds(0)
.includeSubDomains(true);
}
@Bean
public UserDetailsService userDetailsService() {
return (UserDetailsService) username -> {
if (username.equals("server")) {
return new User(username, "",
AuthorityUtils
.commaSeparatedStringToAuthorityList("ROLE_USER"));
} else {
throw new UsernameNotFoundException(String.format("User %s not found", username));
}
};
}
}
}
事情现在都已设置,因此我需要证书和登录名才能正常工作。我相信我在application.yml中具有正确的配置,我尝试使用client-auth:想要或需要,但没有成功。
我敢肯定,有一种更简单的方法来处理此问题。如果有人有解决方案,我将很高兴。
最佳答案
Maintain separate class for cofiguration
关于java - 仅使用Spring Security为某些请求设置多种身份验证方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58854764/