java 如何使用 Spring Security 为特定端点添加 HTTP 基本身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43524211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add HTTP basic auth for a specific endpoint with spring security?
提问by dave
I have a Spring Boot application with Spring Security. A new endpoint /health
is to be configured so it is accessible via basic HTTP authentication. The current HttpSecurity
configuration is as follows:
我有一个带有 Spring Security 的 Spring Boot 应用程序。/health
将配置一个新端点,以便可以通过基本 HTTP 身份验证访问它。目前的HttpSecurity
配置如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers(HttpMethod.OPTIONS, "/**")
.and()
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.permitAll()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
How do I add base auth for /health
? I figure I need something like this, but I don't think this is completely correct, and I don't really understand where exactly to add it:
如何添加基本身份验证/health
?我想我需要这样的东西,但我不认为这是完全正确的,我真的不明白到底在哪里添加它:
.authorizeRequests()
.antMatchers(
// Health status
"/health",
"/health/"
)
.hasRole(HEALTH_CHECK_ROLE)
.and()
.httpBasic()
.realmName(REALM_NAME)
.authenticationEntryPoint(getBasicAuthEntryPoint())
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
I found these resources to be helpful, but not sufficient:
我发现这些资源很有帮助,但还不够:
采纳答案by dave
The solution is to implement multiple configurations, as explained here: https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
解决方案是实现多个配置,如下所述:https: //docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
回答by pvpkiran
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/health/**").hasRole("SOME_ROLE")
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("yourusername").password("yourpassword").roles("SOME_ROLE")
;
}
}