仅验证选定的休息端点:弹簧靴 [英] Authenticate only selected rest end points : spring boot

查看:30
本文介绍了仅验证选定的休息端点:弹簧靴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Spring Boot Web 应用程序,它暴露了几个其余的端点.我想知道我们如何仅对选定的其余端点启用基本身份验证.假设我只希望对 /employee/{id} 请求进行身份验证并忽略所有其他其余端点.我正在使用以下代码.我的问题是 antMatcher 是否只验证指定的请求?目前它为所有其余端点启用身份验证:

I have a Spring Boot web application exposing few rest endpoints. I wanted to know how we can enable basic authentication only for selected rest endpoints. Let's say I want only /employee/{id} request to be authenticated and ignore all the other rest endpoints. I am using the following code. My question is will the antMatcher only authenticate the request specified? Currently its enabling authentication for all rest endpoints:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         // How does it work will it only authenticate employee & 
         // ignore any other request?? Its authenticating all the requests currently. 
         http
            .authorizeRequests()
                 .antMatchers("/employee/*").authenticated()
            .and()
            .httpBasic()
            .and()
            .csrf()
                .disable();    
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }
}

推荐答案

默认情况下,当 Spring Security 在类路径上时,Spring Boot 将保护所有端点.

By default Spring Boot will secure all endpoints when Spring Security is on the classpath.

您需要为所有其他端点明确添加一个排除项,以允许无需身份验证.

You need to explicitly add an exclusion for all other endpoints to be permitted without authentication.

示例:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
               .antMatchers("/employee/*").authenticated()
               .anyRequest().permitAll()
             .and()
             .httpBasic()
             .and()
             .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }

}

这篇关于仅验证选定的休息端点:弹簧靴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆