問題場景:
在spring securit配置類中配置了authenticationEntryPoint()當(dāng)用戶嘗試訪問安全的REST資源而不提供任何憑據(jù)時,將調(diào)用此方法發(fā)送401 響應(yīng),然后使用postmam或者swagger都能正常看見正確的響應(yīng)信息,在網(wǎng)頁中卻出現(xiàn)了跨域問題
/**
* permitAll,會給沒有登錄的用戶適配一個AnonymousAuthenticationToken,設(shè)置到SecurityContextHolder,方便后面的filter可以統(tǒng)一處理authentication
* Spring Security相關(guān)的配置
* 生命周期:在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放行 : 允許匿名和帶權(quán)限以及登錄用戶訪問
.antMatchers(
HttpMethod.resolve(infoEntry.getKey().getMethodsCondition().getMethods().iterator().next().name()),
infoEntry.getKey().getPatternsCondition().getPatterns().toArray(new String[0])[0])
.permitAll();
}
}
httpSecurity
// 禁用 CSRF
.csrf().disable()
// 授權(quán)異常
.exceptionHandling()
.authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> {
// 當(dāng)用戶嘗試訪問安全的REST資源而不提供任何憑據(jù)時,將調(diào)用此方法發(fā)送401 響應(yīng)
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e == null ? "Unauthorized" : e.getMessage());
})
.accessDeniedHandler((httpServletRequest, httpServletResponse, e) -> {
//當(dāng)用戶在沒有授權(quán)的情況下訪問受保護的REST資源時,將調(diào)用此方法發(fā)送403 Forbidden響應(yīng)
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);
// #允許向該服務(wù)器提交請求的URI,*表示全部允許,在SpringMVC中,如果設(shè)成*,會自動轉(zhuǎn)成當(dāng)前請求頭中的Origin
config.addAllowedOriginPattern("*");
// #允許訪問的頭信息,*表示全部
config.addAllowedHeader("*");
// 預(yù)檢請求的緩存時間(秒),即在這個時間段里,對于相同的跨域請求不會再預(yù)檢了
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);
}
前端處理響應(yīng)時卻出現(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)設(shè)置跨域的配置,并且對于一般的請求,我已經(jīng)在Spring security 中進行處理不去對它進行處理(這塊也需要注意,是否進行了配置),此時我的CORS 配置還沒有生效,所以和 spring security 中使用的跨域需要設(shè)置新的變化,Spring Security 其實也是filter 鏈,那就牽扯到 順序的問題
解決
/**
* CROS跨域請求處理方式
*
* @return
*/
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 允許cookies跨域
config.setAllowCredentials(true);
// #允許向該服務(wù)器提交請求的URI,*表示全部允許,在SpringMVC中,如果設(shè)成*,會自動轉(zhuǎn)成當(dāng)前請求頭中的Origin
config.addAllowedOriginPattern("*");
// #允許訪問的頭信息,*表示全部
config.addAllowedHeader("*");
// 預(yù)檢請求的緩存時間(秒),即在這個時間段里,對于相同的跨域請求不會再預(yù)檢了
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;
}
在跨域配置中把跨域配置設(shè)置為最高級別,也就是最早執(zhí)行的,就可以避免部分請求被框架攔截而沒有經(jīng)過跨域配置過濾器,關(guān)鍵代碼filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);