我有一个 Spring Boot Web 应用程序,它公开了几个 rest 端点。我想知道我们如何才能只为选定的其余端点启用基本身份验证。假设我只想对 /employee/{id}
请求进行身份验证,而忽略所有其他其余端点。我正在使用以下代码。我的问题是 antMatcher
是否只验证指定的请求?目前它为所有其余端点启用身份验证:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// How does it work will it only authenticate employee &
// ignore any other request?? Its authenticating all the requests currently.
http
.authorizeRequests()
.antMatchers("/employee/*").authenticated()
.and()
.httpBasic()
.and()
.csrf()
.disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin").roles("USER");
}
}
最佳答案
默认情况下,当 Spring Security 在类路径上时,Spring Boot 将保护所有端点。
您需要为所有其他端点明确添加一个排除项,以便在未经身份验证的情况下被允许。
例子:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/employee/*").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin").roles("USER");
}
}
关于java - 仅验证选定的其余端点 : spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38403740/