Spring Cloud Gateway 整合OAuth2.0 实现统一认证授权
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;
public class AuthorizationGlobalFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获取请求中的Token
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
// 验证Token是否存在或有效
if (token == null || "".equals(token)) {
// Token不存在,返回401 Unauthorized
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return DataBufferUtils.join(response.getBufferFactory())
.flatMap(buffer -> {
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response.writeWith(Mono.just(buffer));
});
}
// Token存在,继续请求
return chain.filter(exchange);
}
}
这段代码定义了一个全局过滤器,用于在Spring Cloud Gateway中实现统一验证访问令牌。如果请求中没有包含有效的Authorization
头信息,则会返回状态码为401的响应。这种方式可以有效地保护微服务架构中的各个服务,确保只有授权的请求能够通过网关访问后端服务。
评论已关闭