1. Add cross-domain configuration in WebMvcConfigurer
Note: addExposedHeader()
Be sure to configure, or front-end will get no response header TOKEN /Authorization
parameters
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true); /*是否允许请求带有验证信息*/
corsConfiguration.addAllowedOrigin("*");/*允许访问的客户端域名*/
corsConfiguration.addAllowedHeader("*");/*允许服务端访问的客户端请求头*/
corsConfiguration.addAllowedMethod("*"); /*允许访问的方法名,GET POST等*/
corsConfiguration.addExposedHeader("token");/*暴露哪些头部信息 不能用*因为跨域访问默认不能获取全部头部信息*/
corsConfiguration.addExposedHeader("TOKEN");
corsConfiguration.addExposedHeader("Authorization");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
Two, configuration modification in SecurityConfig
Add one
Configure to allow cross-domain access, do not add .disable()
;, otherwise the same cannot be accessed
http.cors(); //.disable();
Add two
// 当出现跨域的OPTIONS请求时,发现被拦截,加入下面设置可实现对OPTIONS请求的放行。
http.authorizeRequests().
requestMatchers(CorsUtils::isPreFlightRequest).
permitAll();
}
The current complete authorization code is as follows
/**
* 授权
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 只拦截需要拦截的所有接口, 拦截数据库权限表中的所有接口
List<AdminAuthority> authoritys = adminAuthorityMapper.selectList(null);
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry eiur = http.authorizeRequests();
authoritys.forEach((auth) -> {
eiur.antMatchers(auth.getUrl()).hasAnyAuthority(auth.getUrl());
});
// 配置token验证及登录认证,过滤器
eiur
// 登录接口不需要权限控制,可删除,目前该接口不在权限列表中
.antMatchers("/auth/login", "POST").permitAll()
// 设置JWT过滤器
.and()
.addFilter(new JWTValidFilter(authenticationManager(), resolver))
.addFilter(new JWTLoginFilter(authenticationManager(), resolver)).csrf().disable()
// 剔除session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// 开启跨域访问
http.cors(); //.disable();
// 开启模拟请求,比如API POST测试工具的测试,不开启时,API POST为报403错误
http.csrf().disable();
// iframe 跳转错误处理 Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'deny'
http.headers().frameOptions().disable();
// 当出现跨域的OPTIONS请求时,发现被拦截,加入下面设置可实现对OPTIONS请求的放行。
http.authorizeRequests().
requestMatchers(CorsUtils::isPreFlightRequest).
permitAll();
}
Personal open source project (universal back-end management system) –> https://gitee.com/wslxm/spring-boot-plus2 , if you like, you can read this article. This is the end of this article. If you find it useful, please give a
thumbs up or pay attention to it. , Will continue to update more content from time to time... Thank you for watching!