How do I add HTTP basic auth for a specific endpoint with spring security?

有些话、适合烂在心里 提交于 2020-01-24 02:16:06

问题


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:

@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:

    .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:

  • http://www.baeldung.com/spring-security-basic-authentication
  • http://websystique.com/spring-security/secure-spring-rest-api-using-basic-authentication/

回答1:


The solution is to implement multiple configurations, as explained here: https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity




回答2:


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

        ;
    }

}


来源:https://stackoverflow.com/questions/43524211/how-do-i-add-http-basic-auth-for-a-specific-endpoint-with-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!