什么是跨域访问
在 HTML 中,<a>
, <form>
, <img>
, <script>
, <iframe>
, <link>
等标签以及 Ajax 都可以指向一个资源地址,而所谓的跨域请求就是指:当前发起请求的域与该请求指向的资源所在的域不一样。这里的域指的是这样的一个概念:我们认为若协议 + 域名 + 端口号均相同,那么就是同域。
举个例子:假如一个域名为aaa.cn
的网站,它发起一个资源路径为aaa.cn/books/getBookInfo
的 Ajax 请求,那么这个请求是同域的,因为资源路径的协议、域名以及端口号与当前域一致(例子中协议名默认为http,端口号默认为80)。但是,如果发起一个资源路径为bbb.com/pay/purchase
的 Ajax 请求,那么这个请求就是跨域请求,因为域不一致,与此同时由于安全问题,这种请求会受到同源策略限制。
SpringBoot OAuth2如何支持跨域访问
1.配置WebSecurityConfigurerAdapter
.and().cors().and().csrf().disable();
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.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.ArrayList;
import java.util.List;
@Configuration
@Order(-20)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/try/**").permitAll()
.anyRequest().authenticated()
.and()
.cors()
.and()
.csrf().disable();
}
}
2.编写CORSFilter
package com.ido85.gdc.sso.platform.filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author yin .
* @Date Created Date: 2019/3/21 14:25
* @Description Note:
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials","true");
response.setHeader("Access-Control-Allow-Methods","POST,GET");
response.setHeader("Access-Control-Allow-Max-Age","3600");
response.setHeader("Access-Control-Allow-Headers","*");
if("OPTIONS".equalsIgnoreCase(request.getMethod())){
response.setStatus(HttpServletResponse.SC_OK);
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
}
}
注意:WebSecurityConfigurerAdapter类的@Order注解和CORSFIlter类的@Order注解的执行先后顺序,要让CORSFIlter在前执行,不然会导致接口的{"Authorization":"bearer cd3c26b2-9b24-49a8-af32-192ac1a52015"}校验失败。