package cn.seecoder.devmanage.security; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.CorsUtils; import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig extends WebSecurityConfigurerAdapter { private final JwtAuthenticationFilter jwtAuthenticationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .and() .csrf().disable() .sessionManagement().sessionCreationPolicy(STATELESS) .and() .authorizeRequests() .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() .antMatchers("/limitrequest/student/**").hasAnyAuthority("STUDENT") .anyRequest().hasAnyAuthority("SEEC", "ADMIN") .and() .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } /** * 本地测试时的跨域设置 */ @Bean CorsConfigurationSource corsConfigurationSource() { return httpServletRequest -> { CorsConfiguration cfg = new CorsConfiguration(); cfg.addAllowedOriginPattern("*"); cfg.addAllowedHeader("*"); cfg.addAllowedMethod("*"); cfg.setAllowCredentials(true); cfg.checkOrigin("*"); return cfg; }; } }