需要Spring Security REST Api的基本身份验证单次登录吗?

需要Spring Security REST Api的基本身份验证单次登录吗?,spring,spring-security,Spring,Spring Security,我正在为我的RESTAPI使用SpringSecurityBasicAuth 最初,我获得未经验证的安全路由的未经授权的HTTP响应状态 如果我提供了正确的凭据,我将获得OkHTTP响应状态,但在一次成功登录后,我可以访问所有安全路由,而无需提供用户凭据 以下是我的问题: 这是基本身份验证的正确行为吗 为什么会这样 我的安全配置: @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter

我正在为我的RESTAPI使用SpringSecurityBasicAuth

最初,我获得未经验证的安全路由的未经授权的HTTP响应状态

如果我提供了正确的凭据,我将获得OkHTTP响应状态,但在一次成功登录后,我可以访问所有安全路由,而无需提供用户凭据

以下是我的问题:

  • 这是基本身份验证的正确行为吗
  • 为什么会这样
  • 我的安全配置:

    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserService userService;
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Bean
        public DaoAuthenticationProvider authenticationProvider() {
            DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
            authenticationProvider.setUserDetailsService(userService);
            authenticationProvider.setPasswordEncoder(passwordEncoder());
            return authenticationProvider;
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //J-
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/save")
                    .permitAll()
                    .and()
                    .authorizeRequests()
                    .antMatchers("/h2-console/**")
                    .permitAll()
                    .anyRequest()
                    .authenticated()
                    .and()
                    .httpBasic();
            //J+
    
            //adding support for h2 console, otherwise crashes
            http.headers().frameOptions().disable();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) {
            auth.authenticationProvider(authenticationProvider());
        }
    }
    
    下面是用户详细信息服务的loadByUsername()方法:

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username);
    
        if (user == null) {
            throw new UserNotFoundException(username);
        } else if (UserStatus.Deactivated.equals(user.getStatus())) {
            throw new UserDeactivatedException(username);
        }
    
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.singleton(new SimpleGrantedAuthority("USER")));
    }
    


    参考上面提到的链接。对于Restful API的使用无状态会话策略

    是否发送jsessionid?此外,根据rest约定,api应该是无状态的,所以每次我在postman的cookies中看到jsessionid时,都应该发送auth头。对于restful api,使用无状态会话策略也解决了我的问题。请把它贴出来作为答复,这样我就可以接受了