在集成spring security和vue前后端分离时配置了跨域,也配置了允许携带认证
信息,但是在登录成功,并可以看到返回的用户信息和cookie,但是访问其他接口
时报403
下面是跨域拦截配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:8081");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addExposedHeader(HttpHeaders.COOKIE);
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8081")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTION")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
下面是security设置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
object.setAccessDecisionManager(customAccessDecisionManager);
return object;
}
})
.and().formLogin()
.loginProcessingUrl("/login").permitAll() //指定处理登录请求路径
//指定成功时的处理逻辑
.successHandler((httpServletRequest, httpServletResponse, authentication) -> returnResult(httpServletResponse,jsonResult(authentication)))
.failureHandler((httpServletRequest, httpServletResponse, e) -> returnResult(httpServletResponse,jsonResult(e)))
.and().logout().logoutUrl("/logout").clearAuthentication(true).invalidateHttpSession(true)
.addLogoutHandler((httpServletRequest, httpServletResponse, authentication) -> log.info("you can do something"))
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> returnResult(httpServletResponse,jsonResult()))
.and().addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.cors().and()
.csrf().disable();
}
前端设置
const request = axios.create({
baseURL: window._apiUrl.webUrl,
timeout: 10000,
headers: {
'Content-type': 'application/json',
},
withCredentials: true // 允许携带cookie
})
希望大佬指点