如何支持REST API项目的基本认证和承载认证?

问题描述 投票:1回答:1

我是Spring Security &的新手,还在学习,所以我的问题可能很幼稚,请大家多多包涵。

我有一个Sprint Boot Rest API项目,它暴露了某些API。我已经为所有的API实现了基于bearer token的认证,例如用户、资源、预约等。

现在,对于一个特定的控制器的几个apis,我希望能实现基本的认证,这些apis将被另一个不公开的服务所消耗。这些Apis将被另一个不对外公开的服务所消耗,为了保证API的安全性,我想对这些Apis进行基本的身份验证,例如: internalapi1 , internalapi2 ......等等。

我无法区分尿素在 user &amp.WebSecurityConfigurerAdapter WebSecurityConfigurerAdapter. 也不知道应该用哪个来添加 basicAuth() 使用反匹配器

spring-boot spring-security basic-authentication bearer-token spring-security-rest
1个回答
1
投票

通过阅读你的问题,你想要的是为两个不同的端点提供两种认证类型(token和httpBasic)。这可以通过创建两个不同的WebSecurityConfigurerAdapter Bean来实现。Spring Boot可以实现这一点,可以像下面这样做。

  • @Order(1) - 资源**由承载令牌认证保护。
  • @Order(2) - 由基本认证保护的内部**。

查看文档 弹簧靴 和示例代码 此处.

   @EnableWebSecurity
   public class SecurityConfig {

    @Configuration
    @Order(1)
    public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/resource/**")
                .antMatcher("/user/**")
                .antMatcher("/appointment/**")
                .authorizeRequests()
                    .anyRequest().authenticated()
                .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and().addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        }
    }

    @Configuration
    @Order(2)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/internal/**")
                .and()
                .httpBasic();
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.