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

时间:2019-06-26 19:07:14

标签: spring spring-security

我正在为我的REST API使用Spring Security基本身份验证。

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

如果我提供了正确的凭据,则会得到确定的HTTP响应状态,但是一次成功登录后,我可以访问所有受保护的路由而无需提供用户凭据

这是我的问题:

  1. 基本身份验证是否正确?
  2. 为什么会这样?

我的安全配置:

CTaxGroup

这是 UserDetailsS​​ervice的 loadByUsername()方法:

@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());
    }
}

1 个答案:

答案 0 :(得分:1)

https://www.baeldung.com/spring-security-session

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