2023 11 12 Swagger / Spring Security

XingXi·2023년 11월 12일
0

기록

목록 보기
2/33

🍕 Swagger 정적 리소스 접근 제한

 @Bean
    public SecurityFilterChain securityWebFilterChain(HttpSecurity http) throws Exception {
        return http.csrf(csrf -> csrf.disable()).authorizeHttpRequests(
                auth -> auth.requestMatchers("/api/admin/**").hasRole(MEMBER_ROLE.ADMINISTER.toString())
                        .requestMatchers("/api/mypage/**").authenticated()
                        .requestMatchers("/access-token-create/**").permitAll()
                        .requestMatchers("/login/**").permitAll()
                        .requestMatchers("/swagger-api").permitAll()
                        .requestMatchers("/swagger-ui/**").permitAll())


                .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .formLogin(login -> login.disable())
                .httpBasic(basic -> basic.disable())
                .addFilter(corsFilter())
                .exceptionHandling(handling -> handling
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                        .accessDeniedHandler(jwtAccessDeniedHandler))
                .apply(new JwtSecurityConfig(tokenProvider)).and()
                .build();
    }

다음과 같이 Spring Config 설정을 하지 않아서 Swagger 가 정상적으로 작동하지 않는 상황
정적 Resource 를 등록해서 사용하려다가 인증, 인가가 필요한 부분만 Security Config 에 등록하고 나머지는 permitAll 해서 설정

    @Bean
    public SecurityFilterChain securityWebFilterChain(HttpSecurity http) throws Exception {
        return http.csrf(csrf -> csrf.disable()).authorizeHttpRequests(
                auth -> auth.requestMatchers("/api/admin/**").hasRole(MEMBER_ROLE.ADMINISTER.toString())
                        .requestMatchers("/api/mypage/**").authenticated()
                        .requestMatchers("/access-token-create/**").permitAll()
                        .requestMatchers("/login/**").permitAll()
                        .requestMatchers("/swagger-api").permitAll()
                        .requestMatchers("/swagger-ui/**").permitAll()
                        .anyRequest().permitAll())

                .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .formLogin(login -> login.disable())
                .httpBasic(basic -> basic.disable())
                .addFilter(corsFilter())
                .exceptionHandling(handling -> handling
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                        .accessDeniedHandler(jwtAccessDeniedHandler))
                .apply(new JwtSecurityConfig(tokenProvider)).and()
                .build();
    }

.anyRequest().permitAll())

0개의 댓글