我有一个基于Spring-Boot版本构建的仅REST微服务1.5.4.RELEASEspring-boot-starter-security。该服务没有网页,只有JSON输入和输出。用户名和密码在application.properties文件中配置。值得称赞的是http://ryanjbaxter.com/2015/01/06/securing-rest-apis-with-spring-boot/以下配置使服务器很好地实现了基本的HTTP身份验证,它接受凭据并拒绝未经授权的请求:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests() //
.anyRequest().authenticated().and().httpBasic();
}
}
我的问题是,我想从基本HTTP认证中排除一个小ole路径,一个小endpoint。通过疯狂的谷歌搜索和复制粘贴,我修改了上面的内容:
http.csrf().disable().authorizeRequests() //
.antMatchers("/healthcheck").permitAll()
.anyRequest().authenticated().and().httpBasic();
这会在没有警告的情况下编译和运行,但不会打开该路径进行未经验证的访问。我仍然必须提供凭据以检查服务运行状况。
我必须一个一个地匹配路径吗?我的小healthcheckendpoint在上下文路径的基础上,就像一大堆其他endpoint一样——逐个添加路径会很麻烦。
我申请的相关部分。属性文件是:
security.user.name = web-user
security.user.password = web-pass
management.security.roles=SUPERUSER
也许我需要摆弄一下角色?
请帮忙,提前谢谢。
更新1:
路径信息-我希望这个路径(以及更多的根)被保护:
localhost:8081/abcd/user
我只希望这一条路径是开放的,不需要身份验证:
localhost:8081/abcd/healthcheck
更新2:看起来我在很大程度上重复了这个3年前的问题,但我的问题没有答案被接受:
单个web应用程序路径上的spring-boot设置基本身份验证?
经过更多的实验,我发现以下工作 - @efekctive请注意,运行状况检查上没有上下文前缀:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/healthcheck").permitAll()
.antMatchers("/**").authenticated().and().httpBasic();
}
一个大警告:当我发布此消息时,我正在测试healthcheckendpoint,通过使用伪造的http凭据调用curl,期望Spring忽略它们,但Spring总是回答401未经授权。正确的测试是在完全没有http凭据的情况下调用curl,然后healthcheckendpoint非常满意地回答。
我已将以下内容添加到我的Springboot服务中的SecurityConfig中,并且它工作正常,我能够从基本身份验证中排除某些endpoint。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/customers/**/hints", "/customers/**/search", "/customers/**/clientConfig");
}
你说你的链接看起来像:
localhost:8081/abcd/healthcheck
试试这个:
http.csrf().disable().authorizeRequests() //
.antMatchers("/abcd/healthcheck").permitAll()
.anyRequest().authenticated().and().httpBasic();