У меня есть одностраничное приложение Vue, обслуживаемое Nginx, которое направляет вызовы API в облачный шлюз Spring. API входа в систему возвращает токен JWT в печенье. Nginx картирует это cookie в заголовок авторизации и передает его в шлюз, и я также снова вводит один и тот же заголовок в пользовательский глобальныйфильтер. Несмотря на то, что правильный авторизация: носитель как в сетевой панели, так и в журналах шлюза, фронт по -прежнему немедленно перенаправляет обратно в /вход после каждого запроса. < /P>
Ниже приведены все соответствующие конфигурации и фрагменты кода. < /P>
[*]nginx.conf
< /ol>
nginx.conf < /ol>
< Li>nginx.conf> < /ol>
написана.worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/json;
sendfile on;
keepalive_timeout 65;
# Map the `token` cookie into an Authorization header
map $cookie_token $auth_header {
default "";
"~.+" "Bearer $cookie_token";
}
server {
listen 18080;
server_name localhost;
# Serve Vue static files
location / {
root html/hmall-portal;
try_files $uri $uri/ =404;
}
# Proxy all /api/ calls to Spring Cloud Gateway
location /api/ {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://localhost:8088/;
proxy_set_header Host $host;
proxy_set_header Authorization $auth_header;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# CORS (optional for development)
add_header Access-Control-Allow-Origin http://localhost:18080;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Headers Content-Type,Authorization;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
if ($request_method = OPTIONS) {
return 204;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
< /code>
2.authglobalfilter.java
@Slf4j
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {
private final JwtTool jwtTool;
private final AuthProperties authProperties;
private final AntPathMatcher pathMatcher = new AntPathMatcher();
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
// 1. Skip excluded paths (login, register, search, etc.)
String path = request.getPath().value();
for (String pattern : authProperties.getExcludePaths()) {
if (pathMatcher.match(pattern, path)) {
return chain.filter(exchange);
}
}
// 2. Extract token: first try Authorization header, then `token` cookie
String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
log.info(">>> Authorization after inject: {}", authHeader);
String token = null;
if (StringUtils.hasText(authHeader)) {
token = authHeader.startsWith("Bearer ")
? authHeader.substring(7)
: authHeader;
}
if (token == null) {
List cookies = request.getCookies().get("token");
if (cookies != null && !cookies.isEmpty()) {
token = cookies.get(0).getValue();
}
}
ServerHttpResponse response = exchange.getResponse();
if (token == null) {
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
// 3. Validate JWT
Long userId;
try {
userId = jwtTool.parseToken(token);
} catch (UnauthorizedException ex) {
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
// 4. Inject user-info header and continue
ServerWebExchange mutated = exchange.mutate()
.request(r -> r.header("user-info", userId.toString()))
.build();
return chain.filter(mutated);
}
@Override
public int getOrder() {
return 0;
}
}
< /code>
3.application.yml
server:
port: 8088
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: 192.168.200.128:8848
locator:
enabled: true
lower-case-service-id: true
gateway:
routes:
- id: item-service
uri: lb://item-service
predicates:
- Path=/items/**,/search/**
- id: cart-service
uri: lb://cart-service
predicates:
- Path=/carts/**
- id: user-service
uri: lb://user-service
predicates:
- Path=/users/**,/addresses/**
default-filters:
- AddRequestHeader=key,value
hm:
jwt:
secret: hmall123 # Must match the secret used by user-service
location: classpath:hmall.jks
alias: hmall
password: hmall123
tokenTTL: 30m
auth:
excludePaths:
- /search/**
- /users/login
- /items/**
- /hi
< /code>
4.shonsole журнал Оператор журнала : < /p>
2025-04-28 21:27:17.016 INFO 16436 --- [ main] com.hmall.gateway.GatewayApplication : Starting GatewayApplication using Java 11.0.0.2 on MateBook14 with PID 16436 (D:\QuickCache\资料\hmall\hm-gateway\target\classes started by ding in D:\QuickCache\资料\hmall)
2025-04-28 21:27:17.019 INFO 16436 --- [ main] com.hmall.gateway.GatewayApplication : No active profile set, falling back to 1 default profile: "default"
2025-04-28 21:27:17.900 INFO 16436 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=66cfd6b9-c338-3b1e-b895-7288e9cc55de
2025-04-28 21:27:17.986 INFO 16436 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2025-04-28 21:27:17.987 INFO 16436 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2025-04-28 21:27:17.990 INFO 16436 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'reactorDeferringLoadBalancerExchangeFilterFunction' of type [org.springframework.cloud.client.loadbalancer.reactive.DeferringLoadBalancerExchangeFilterFunction] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [After]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Before]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Between]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Cookie]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Header]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Host]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Method]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Path]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Query]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [ReadBody]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [RemoteAddr]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [XForwardedRemoteAddr]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Weight]
2025-04-28 21:27:19.347 INFO 16436 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [CloudFoundryRouteService]
2025-04-28 21:27:19.940 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [RpcClientFactory] create a new rpc client of 7370ffe6-0875-4fa3-a896-633a996d1512
2025-04-28 21:27:19.997 INFO 16436 --- [ main] org.reflections.Reflections : Reflections took 29 ms to scan 1 urls, producing 3 keys and 6 values
2025-04-28 21:27:20.027 INFO 16436 --- [ main] org.reflections.Reflections : Reflections took 11 ms to scan 1 urls, producing 4 keys and 9 values
2025-04-28 21:27:20.038 INFO 16436 --- [ main] org.reflections.Reflections : Reflections took 7 ms to scan 1 urls, producing 3 keys and 10 values
2025-04-28 21:27:20.046 WARN 16436 --- [ main] org.reflections.Reflections : given scan urls are empty. set urls in the configuration
2025-04-28 21:27:20.056 INFO 16436 --- [ main] org.reflections.Reflections : Reflections took 9 ms to scan 1 urls, producing 1 keys and 5 values
2025-04-28 21:27:20.069 INFO 16436 --- [ main] org.reflections.Reflections : Reflections took 7 ms to scan 1 urls, producing 1 keys and 7 values
2025-04-28 21:27:20.083 INFO 16436 --- [ main] org.reflections.Reflections : Reflections took 8 ms to scan 1 urls, producing 2 keys and 8 values
2025-04-28 21:27:20.086 WARN 16436 --- [ main] org.reflections.Reflections : given scan urls are empty. set urls in the configuration
2025-04-28 21:27:20.088 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] RpcClient init label, labels = {module=naming, source=sdk}
2025-04-28 21:27:20.091 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] RpcClient init, ServerListFactory = com.alibaba.nacos.client.naming.core.ServerListManager
2025-04-28 21:27:20.091 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Registry connection listener to current client:com.alibaba.nacos.client.naming.remote.gprc.redo.NamingGrpcRedoService
2025-04-28 21:27:20.092 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Register server push request handler:com.alibaba.nacos.client.naming.remote.gprc.NamingPushRequestHandler
2025-04-28 21:27:20.094 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Try to connect to server on start up, server: {serverIp = '192.168.200.128', server main port = 8848}
2025-04-28 21:27:21.336 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Success to connect to server [192.168.200.128:8848] on start up, connectionId = 1745844725690_192.168.200.1_8561
2025-04-28 21:27:21.337 INFO 16436 --- [t.remote.worker] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Notify connected event to listeners.
2025-04-28 21:27:21.340 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Register server push request handler:com.alibaba.nacos.common.remote.client.RpcClient$ConnectResetRequestHandler
2025-04-28 21:27:21.340 INFO 16436 --- [ main] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Register server push request handler:com.alibaba.nacos.common.remote.client.RpcClient$$Lambda$787/0x000000080062d440
2025-04-28 21:27:21.715 INFO 16436 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port 8088
2025-04-28 21:27:21.877 INFO 16436 --- [ient-executor-6] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Receive server push request, request = NotifySubscriberRequest, requestId = 134
2025-04-28 21:27:21.896 INFO 16436 --- [ient-executor-6] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Ack server push request, request = NotifySubscriberRequest, requestId = 134
2025-04-28 21:27:22.121 INFO 16436 --- [ main] c.a.c.n.registry.NacosServiceRegistry : nacos registry, DEFAULT_GROUP gateway 10.81.175.75:8088 register finished
2025-04-28 21:27:22.142 INFO 16436 --- [ main] com.hmall.gateway.GatewayApplication : Started GatewayApplication in 6.178 seconds (JVM running for 7.075)
2025-04-28 21:27:22.641 INFO 16436 --- [ent-executor-10] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Receive server push request, request = NotifySubscriberRequest, requestId = 135
2025-04-28 21:27:22.661 INFO 16436 --- [ent-executor-10] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Ack server push request, request = NotifySubscriberRequest, requestId = 135
2025-04-28 21:27:29.751 INFO 16436 --- [ent-executor-13] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Receive server push request, request = NotifySubscriberRequest, requestId = 136
2025-04-28 21:27:29.752 INFO 16436 --- [ent-executor-13] com.alibaba.nacos.common.remote.client : [7370ffe6-0875-4fa3-a896-633a996d1512] Ack server push request, request = NotifySubscriberRequest, requestId = 136
2025-04-28 21:27:30.619 INFO 16436 --- [ctor-http-nio-5] c.h.gateway.filters.AuthGlobalFilter : >>> Authorization after inject: Bearer eyJhbGciOiJIUzI1NiJ9.eyJlbXBJZCI6MSwiZXhwIjoxNzQzMjQ2Mjg4fQ.t1XbZjUXHAQvIDPGkVR9WtPDQOQ7TkteNe78wxEYNk8
Подробнее здесь: https://stackoverflow.com/questions/795 ... ck-to-logi
Весенний облачный шлюз ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Неверный токен CSRF при вызове микросервисов через мой весенний облачный шлюз
Anonymous » » в форуме JAVA - 0 Ответы
- 4 Просмотры
-
Последнее сообщение Anonymous
-