需求:需要服务器提供两个端口访问请求,然后打到nginx上转发到前台,再打到ngxin上,转发到后台请求数据返回
看似简单,实则因为项目中有springSecuirty路由过滤或者ngxin路由配置中/的问题导致跨域,过滤器拦截返回等
首先附上最后正确的nginx配置文件,然后在一一叙述坑:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
# 允许跨域GET,POST,DELETE HTTP方法发起跨域请求
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
if ($request_method = OPTIONS){
return 200;
}
#端口号1
listen 9000;
server_name 172.16.1.164;
location / {
root "E:\工程材料管理\前台\172.16.1.164 9000 api";
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^(.*) /index.html last;
break;
}
location /api/ {
proxy_pass http://172.16.1.164:8005/api/;
}
}
}
server {
if ($request_method = OPTIONS){
return 200;
}
#端口号2
listen 9001;
server_name 172.16.1.164;
location / {
root "E:\工程材料管理\前台\172.16.1.164 9001 api";
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^(.*) /index.html last;
break;
}
location /api/ {
proxy_pass http://172.16.1.164:8005/api/;
}
}
}
}
- 这里nginx没有配置跨域,因为后台服务已经配置跨域
如果重复配置,浏览器会报错:
package com.demo.app.config.webmvc;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import javax.annotation.Resource;
/**
* 类功能描述: CorsConfig
*
* @author Eternal
* @date 2019-11-26 15:11
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Value("${spring.servlet.multipart.location}")
private String path;
/**
* 跨域配置
*
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "DELETE", "OPTIONS")
.maxAge(3600)
// 是否允许发送Cookie
.allowCredentials(true)
.allowedHeaders("*");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 静态文件
registry.addResourceHandler("**").addResourceLocations("classpath:/static/");
// swagger
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// 上传文件
registry.addResourceHandler("/file/**").addResourceLocations("file:/" + path);
}
}
- 前端路由末尾没有/ 导致一直报跨域
3. 最后说一下springSecuirty中路由拦截
springSecuity的配置文件中路由拦截一定要和nginx配置的路由转发匹配上,要不然转发过来security的过滤器直接过滤了,也请求不到接口,注意到我这里使用了/api的前缀,在controller中都是用/api前缀,方便ngxin匹配,前台也一样
package com.demo.app.config.security;
import com.demo.app.config.jwt.JWTAuthorizationFilter;
import com.demo.app.config.security.handle.AuthenticationEntryPointImpl;
import com.demo.app.config.security.handle.LogoutSuccessHandlerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.annotation.Resource;
/**
* @program: spring-security
* @description:
* @author: fbl
* @create: 2020-12-01 14:40
**/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* jwt——token认证过滤器
*/
@Autowired
JWTAuthorizationFilter authorizationFilter;
/**
* 退出处理类
*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
/**
* 自定义用户认证逻辑
*/
@Resource
private UserDetailsService userDetailsService;
/**
* 解决 无法直接注入 AuthenticationManager
*
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
// 禁用 CSRF
.csrf().disable()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 防止iframe 造成跨域
.headers()
.frameOptions()
.disable()
// 不创建会话
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and();
http
.authorizeRequests() // 授权配置
// 自定义匿名访问所有url放行 : 允许匿名和带权限以及登录用户访问
// 阿里巴巴 druid
.antMatchers("/api/login/").permitAll()
.antMatchers("/api/file/**").permitAll()
.antMatchers("/druid/**").permitAll()
.antMatchers("/default/**").permitAll()
.antMatchers("/").permitAll()
// swagger 文档
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("swagger/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/swagger-ui.html/*").permitAll()
.antMatchers("/swagger-resources").permitAll()
.antMatchers("/*/api-docs").permitAll()
.antMatchers("/v2/api-docs-ext").permitAll()
// 静态资源等等
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/**/*.svg",
"/**/*.ico",
"/**/*.png",
"/**/*.jpg",
"/**/*.xlsx",
"/webSocket/**"
).permitAll()
// anyRequest 只能配置一个,多个会报错
//其他接口需要登录后才能访问
.anyRequest().authenticated()
.and()
// 退出
.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler)
.and()
// token认证
.addFilterBefore(authorizationFilter, UsernamePasswordAuthenticationFilter.class);
}
/**
* 自定义用户名和密码有2种方式,一种是在代码中写死 另一种是使用数据库
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 身份认证接口
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
补充:
又遇到了一个问题:
Apache、IIS、Nginx等绝大多数web服务器,都不允许静态文件响应POST请求,否则会返回“HTTP/1.1 405 Method not allowed”错误。
nginx修改过后的配置文件:
主要是:
error_page 405 =200 @405;
location @405 {
proxy_method GET;
proxy_pass http://172.16.1.100:8001;
}
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
# 允许跨域GET,POST,DELETE HTTP方法发起跨域请求
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
#端口号1
listen 18121;
server_name 58.213.83.186;
if ($request_method = OPTIONS){
return 200;
}
error_page 405 =200 @405;
location @405 {
proxy_method GET;
proxy_pass http://58.213.83.186:18121;
}
location / {
root "D:\工程管理\前台\公网";
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^(.*) /index.html last;
break;
}
}
location /api/ {
proxy_pass http://172.16.1.100:8005/api/;
}
}
server {
#端口号2
listen 8000;
server_name 172.16.1.100;
if ($request_method = OPTIONS){
return 200;
}
error_page 405 =200 @405;
location @405 {
proxy_method GET;
proxy_pass http://172.16.1.100:8001;
}
if ($request_method = OPTIONS){
return 200;
}
location / {
root "D:\工程管理\前台\私网";
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^(.*) /index.html last;
break;
}
}
location /api/ {
proxy_pass http://172.16.1.100:8005/api/;
}
}
}