我如何向身份验证URL添加许可,antMatchers和securityMatchers不起作用

p8ekf7hl  于 2022-12-26  发布在  Spring
关注(0)|答案(1)|浏览(299)
@Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                    .cors()
                    .and()
                    .csrf().disable()
                    //.authorizeHttpRequests((auth) -> auth
                    //      .requestMatchers("/auth/**")
                    //      .permitAll()
                    //      .anyRequest()
                    //      .authenticated())
                    //.httpBasic()
                    .authorizeHttpRequests()//insted of the commented code
                    .anyRequest()//insted of the commented code
                    .authenticated()//insted of the commented code
                    .and()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authenticationProvider(authenticationProvider())
                    .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

            return http.build();
        }

这是代码,我无法添加antMatcher/antMatchers,因为它找不到它,并且使用注解部分和securetyMatcher,我只能在/auth/login上获得禁止的请求
IM使用 Spring Boot 3.0.0
我试过

http
                .cors()
                .and()
                .csrf().disable()
                .authorizeHttpRequests((auth) -> auth
                        .requestMatchers("/auth/login", "POST").permitAll()
                )
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider())
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

也只有

.authorizeHttpRequests((auth) -> auth
                        .requestMatchers("/auth/login", "POST").permitAll()
                )

仍然禁止

cbwuti44

cbwuti441#

事实上,您的端点必须受到保护。
像这样试试

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .cors().and().csrf().disable()
        .authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/auth/**").permitAll()
            .anyRequest().authenticated()
        )
        .and()       
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authenticationProvider(authenticationProvider())
        .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
}

使用此配置,您可以授权任何用户访问“/auth/*”端点,并保护所有其他用户。

相关问题