不带WebSecurityConfigurerAdapter的SecurityConfig类

lx0bsm1f  于 2023-08-05  发布在  Spring
关注(0)|答案(2)|浏览(105)

我正在上一门 Spring 课程,教授用的是一种老式的 Spring Boot 。我尝试使用最新版本,但它在安全部分有一些差异,我遇到了麻烦。
最大的问题是在没有扩展WebConfigurerAdapter的情况下实现SecurityConfig。

这是老师的例子:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] PUBLIC_MATCHERS = { "/h2-console/**" };

    @Autowired
    private Environment env;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if (Arrays.asList(env.getActiveProfiles()).contains("test")) {
            http.headers().frameOptions().disable();
        }

        http.cors().and().csrf().disable();
        http.authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated();

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

字符串

这就是我所做的:

@EnableWebSecurity
@Configuration
public class SecurityConfig  {
private static final String[] PUBLIC_MATCHERS = {"/h2-console/**"};

    @Autowired
    private Environment env;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //desliga a protecao a csrf, o que permite executar metodos POST,PUT,DELETE sem sessao de usuario
        http.authorizeHttpRequests().requestMatchers(PathRequest.toH2Console()).permitAll().and().headers().frameOptions().disable(); //libera acesso ao h2-console
http.cors();

return http.build();
}


当我尝试访问“http://localhost:8080/h2-console/”时,它正常工作,但如果我尝试访问其他内容,则返回错误403 Forbidden
根据课程,如果我尝试访问不同于“h2-console”的内容,它应该重定向到登录页面(浏览器)或返回错误401 Unauthorized(postman),例如:login page
我应该改变什么才能像预期的那样工作?

wgeznvg7

wgeznvg71#

安全配置文件:

@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
public class SecurityConfig {

    private final UserDetailServiceImpl userDetailsService;

    private final BCryptPasswordEncoder encoder;

    private final JwtFilter filter;

    private final JwtAuthenticationEntryPoint point;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.csrf(csrf -> csrf.disable())
                .authorizeRequests().
                requestMatchers("/category/add")
                .authenticated()
                .requestMatchers("/authenticate","/register").permitAll()
                .anyRequest()
                .authenticated()
                .and().exceptionHandling(ex -> ex.authenticationEntryPoint(point))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

 @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return new CustomAuthenticationManager();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(encoder);
        return authenticationProvider;
    }
}

字符串
CustomAuthenticationManager

public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    private DaoAuthenticationProvider authenticationProvider;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        return authenticationProvider.authenticate(authentication);
    }
}

7hiiyaii

7hiiyaii2#

您必须禁用frameOptions并允许h2端点。另外,如果你要使用swagger等,你也必须允许它的端点。下面是工作示例:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {

  ............
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .headers().frameOptions().disable().and()
                .csrf().disable()
                .cors().and()
                .authorizeRequests(auth -> {
                    auth.antMatchers("/api/admin").hasAuthority("ADMIN");
                    auth.antMatchers("/api/user").hasAnyAuthority("ADMIN", "USER");
                    auth.anyRequest().authenticated();
                })
                .formLogin().disable()
                .httpBasic().disable()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/api/public",
                "/h2-console/**",
                "/swagger-resources/**",
                "/swagger-ui.html/**",
                "/swagger-resources/**",
                "/swagger-ui/**",
                "/v3/api-docs/**");
    }

}

字符串

相关问题