問題場景:
在spring securit配置類中配置了authenticationEntryPoint()
當用戶嘗試訪問安全的REST資源而不提供任何憑據(jù)時陷嘴,將調(diào)用此方法發(fā)送401 響應濒析,然后使用postmam或者swagger都能正臣诟澹看見正確的響應信息,在網(wǎng)頁中卻出現(xiàn)了跨域問題
/**
* permitAll匾南,會給沒有登錄的用戶適配一個AnonymousAuthenticationToken宋光,設置到SecurityContextHolder,方便后面的filter可以統(tǒng)一處理authentication
* Spring Security相關的配置
* 生命周期:在spring容器啟動時加載
*
* @param httpSecurity
* @throws Exception
*/
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// 搜尋匿名標記 url: @AnonymousAccess 篩選出HandlerMapping中url映射方法帶自定義注解 @AnonymousAccess 的url示括,進行過濾
Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = SpringContextHolder.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
HandlerMethod handlerMethod = infoEntry.getValue();
if (null != handlerMethod.getMethodAnnotation(AnonymousAccess.class)) {
httpSecurity.
authorizeRequests()
// 自定義匿名訪問所有url放行 : 允許匿名和帶權限以及登錄用戶訪問
.antMatchers(
HttpMethod.resolve(infoEntry.getKey().getMethodsCondition().getMethods().iterator().next().name()),
infoEntry.getKey().getPatternsCondition().getPatterns().toArray(new String[0])[0])
.permitAll();
}
}
httpSecurity
// 禁用 CSRF
.csrf().disable()
// 授權異常
.exceptionHandling()
.authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> {
// 當用戶嘗試訪問安全的REST資源而不提供任何憑據(jù)時,將調(diào)用此方法發(fā)送401 響應
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e == null ? "Unauthorized" : e.getMessage());
})
.accessDeniedHandler((httpServletRequest, httpServletResponse, e) -> {
//當用戶在沒有授權的情況下訪問受保護的REST資源時痢畜,將調(diào)用此方法發(fā)送403 Forbidden響應
httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
})
// 防止iframe 造成跨域
.and()
.headers()
.frameOptions()
.disable()
// 不創(chuàng)建會話
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//放行請求和添加過濾器
.and()
.authorizeRequests()
// 所有請求都需要認證
.anyRequest().authenticated()
.and().apply(new SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>() {
@Override
public void configure(HttpSecurity http) {
http.addFilterBefore(new JwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
);
盡管我已經(jīng)配置了統(tǒng)一的跨域配置
/**
* CROS跨域請求處理方式
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 允許cookies跨域
config.setAllowCredentials(true);
// #允許向該服務器提交請求的URI垛膝,*表示全部允許,在SpringMVC中丁稀,如果設成*吼拥,會自動轉成當前請求頭中的Origin
config.addAllowedOriginPattern("*");
// #允許訪問的頭信息,*表示全部
config.addAllowedHeader("*");
// 預檢請求的緩存時間(秒),即在這個時間段里线衫,對于相同的跨域請求不會再預檢了
config.setMaxAge(18000L);
// 允許提交請求的方法類型凿可,*表示全部允許
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
前端處理響應時卻出現(xiàn)跨域問題
Access to XMLHttpRequest at 'http://localhost:8081/user/detailInfo' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
思考:
首先回想跨域問題,其實我已經(jīng)設置跨域的配置授账,并且對于一般的請求枯跑,我已經(jīng)在Spring security 中進行處理不去對它進行處理(這塊也需要注意,是否進行了配置)白热,此時我的CORS 配置還沒有生效敛助,所以和 spring security 中使用的跨域需要設置新的變化,Spring Security 其實也是filter 鏈屋确,那就牽扯到 順序的問題
解決
/**
* CROS跨域請求處理方式
*
* @return
*/
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 允許cookies跨域
config.setAllowCredentials(true);
// #允許向該服務器提交請求的URI纳击,*表示全部允許,在SpringMVC中攻臀,如果設成*焕数,會自動轉成當前請求頭中的Origin
config.addAllowedOriginPattern("*");
// #允許訪問的頭信息,*表示全部
config.addAllowedHeader("*");
// 預檢請求的緩存時間(秒),即在這個時間段里茵烈,對于相同的跨域請求不會再預檢了
config.setMaxAge(18000L);
// 允許提交請求的方法類型抛杨,*表示全部允許
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(source));
// 代表這個過濾器在眾多過濾器中級別最高国撵,也就是過濾的時候最先執(zhí)行
filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return filterRegistrationBean;
}
在跨域配置中把跨域配置設置為最高級別瞄沙,也就是最早執(zhí)行的忘嫉,就可以避免部分請求被框架攔截而沒有經(jīng)過跨域配置過濾器显蝌,關鍵代碼filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);