Gateway网关分布式微服务认证鉴权
在分布式微服务系统中,鉴权通常在API网关进行。以下是一个简化的Spring Cloud Gateway实现,使用了内置的过滤器和全局过滤器链来实现鉴权。
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
public class AuthGlobalFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 从请求中获取认证信息,例如Token
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
// 验证token是否有效
boolean isTokenValid = validateToken(token);
if (isTokenValid) {
// Token有效,继续请求
return chain.filter(exchange);
} else {
// Token无效,返回401 Unauthorized
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().set("Content-Type", "application/json");
String body = "{\"message\":\"Invalid or missing token\"}";
DataBufferUtils.write(response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8)), response.getBody());
return Mono.empty();
}
}
private boolean validateToken(String token) {
// 这里只是示例,实际应该查询认证服务或者进行其他验证
return "valid-token".equals(token);
}
}
然后,你需要将这个全局过滤器注册到网关服务中:
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public AuthGlobalFilter authGlobalFilter() {
return new AuthGlobalFilter();
}
}
这样,每个通过网关的请求都会先经过鉴权过滤器,只有验证通过的请求才会被转发到后端的微服务。如果鉴权失败,请求会返回401 Unauthorized响应。
评论已关闭