如何使用spring security为特定端点添加HTTP基本身份验证?

时间:2017-04-20 15:44:41

标签: java spring http security

我有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);

}

如何为/health添加基本身份验证?我想我需要这样的东西,但我不认为这是完全正确的,我真的不明白在哪里添加它:

    .authorizeRequests()
    .antMatchers(
        // Health status
        "/health",
        "/health/"
    )
    .hasRole(HEALTH_CHECK_ROLE)
    .and()
    .httpBasic()
    .realmName(REALM_NAME)
    .authenticationEntryPoint(getBasicAuthEntryPoint())
    .and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

我发现这些资源很有帮助,但还不够:

2 个答案:

答案 0 :(得分:5)

答案 1 :(得分:0)

@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")

        ;
    }

}