Spring 引导安全性 禁用特定 URL 的 Web 安全性



我正在为包含一组 Restful 服务的 Spring Boot 应用程序使用 Spring 安全性。我已通过基本身份验证启用了 Web 安全性。 我想启用基本身份验证,但以特定模式结尾的特定 API URL 除外。(例如,运行状况检查 API,例如:/application/_healthcheck(

代码如下所示:

@Configuration
@EnableWebSecurity
public class ApplicationWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authEntryPoint;
@Value("${application.security.authentication.username}")
private String username;
@Value("${application.security.authentication.password}")
private String password;
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
}
@Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(username).password(password).roles("USER");
}
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("*/_healthcheck");
}
}

但是,每当我调用 .../application/_healthcheck URL 时,浏览器总是提示我输入凭据。

或者,我什至尝试从 Spring boot 的应用程序属性中忽略此路径(使用 web.ignoring((.antMatchers("*/_healthcheck"(删除了配置方法(,但仍然无法摆脱此端点的身份验证

security.ignored=/_healthcheck,*/_healthcheck

您可以创建权限列表并使用它来禁用安全性。

List<String> permitAllEndpointList = Arrays.asList(
AUTHENTICATION_URL,
REFRESH_TOKEN_URL,
EXTERNAL_AUTH_URL,
"/swagger-resources",
"/swagger-resources/**",
"/swagger-ui.html"
);

,然后将此语句添加到 HttpSecurity 对象

.and()
.authorizeRequests()
.antMatchers(permitAllEndpointList.toArray(new String[permitAllEndpointList.size()]))
.permitAll()

这将解决您的问题。

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/application/_healthcheck");
}

上述示例和您的代码的区别在于web的使用超过了http。尝试使用网络,看看它是否有效{实际上它应该:)}。

试试这个。这将跳过运行状况 URL 的身份验证部分。

@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("*/_healthcheck").permitAll() // added this line
.anyRequest().authenticated()
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
}

最新更新