微服务鉴权中心之网关配置SpringSecurity+oauth2

微服务鉴权中心流程如下:

  1. 网关配置oauth2之TokenStore存储方式,此处用RedisTokenStore
java 复制代码
@Configuration

public class TokenConfig {

    @Autowired

    private RedisConnectionFactory redisConnectionFactory;

    @Bean

    public TokenStore tokenStore() {

        return new RedisTokenStore(redisConnectionFactory);

    }

 }

2.网关配置security

java 复制代码
@EnableWebFluxSecurity
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) {
        return http.authorizeExchange()
                .pathMatchers("/**").permitAll()
                .anyExchange().authenticated()
                .and().csrf().disable().build();
    }
}

3.网关拦截token

java 复制代码
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


@Component
@Slf4j
public class GatewayFilterConfig implements GlobalFilter, Ordered {

    @Autowired
    private TokenStore tokenStore;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestUrl = exchange.getRequest().getPath().value();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        //1 oauth服务接口放行
        if (pathMatcher.match("/auth/oauth/**", requestUrl)) {
            return chain.filter(exchange);
        }
        //2 检查token是否存在
        String token = getToken(exchange);
        if (StringUtils.isBlank(token)) {
            return noTokenMono(exchange);
        }
        //3 判断是否是有效的token
        OAuth2AccessToken oAuth2AccessToken;
        try {
            oAuth2AccessToken = tokenStore.readAccessToken(token);
            if (oAuth2AccessToken == null) { 
                return invalidTokenMono(exchange);
            }
        } catch (InvalidTokenException e) {           
            return invalidTokenMono(exchange);
        } catch (Exception e) {         
            return invalidTokenMono(exchange);
        }
        return chain.filter(exchange);
    }

    private String getToken(ServerWebExchange exchange) {
        String tokenStr = exchange.getRequest().getHeaders().getFirst("IPC-TOKEN");
        if (StringUtils.isBlank(tokenStr)) {
            return null;
        }
        String token = tokenStr.split(" ")[1];
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return token;
    }


    private Mono<Void> invalidTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.UNAUTHORIZED.value());
        json.put("data", "无效的token");
        return buildReturnMono(json, exchange);
    }

    private Mono<Void> noTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.UNAUTHORIZED.value());
        json.put("data", "没有token");
        return buildReturnMono(json, exchange);
    }


    private Mono<Void> buildReturnMono(JSONObject json, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bits = json.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
相关推荐
掘根11 分钟前
【微服务即时通讯】好友管理子服务2
微服务·云原生·架构
ai产品老杨21 分钟前
异构计算时代的架构突围:基于 Docker 的 AI 视频平台如何实现 X86/ARM 与 GPU/NPU 全兼容(源码交付)
人工智能·docker·架构
一叶飘零_sweeeet1 小时前
接口安全:签名、加密、防重放架构方案
安全·架构
CinzWS1 小时前
中断向量表中断号与 CMSIS IRQn 映射关系深度剖析:从硬件索引到软件句柄的桥梁
arm开发·架构·系统架构·嵌入式·cortex-m3·中断
The Open Group1 小时前
在复杂时代设计组织:架构思维的未来
架构
向量引擎2 小时前
肝了三天三夜!四大AI模型(DeepSeek/Gemini/ChatGPT/豆包)深度横评,开发者该如何选?
人工智能·chatgpt·架构·开源·aigc·文心一言·api调用
小温冲冲2 小时前
Qt WindowContainer 进阶指南:底层原理、性能优化与架构抉择
qt·性能优化·架构
nbsaas-boot3 小时前
AI编程的现实困境与未来路径:从“可用”到“可靠”的跃迁
java·运维·开发语言·架构
文言AI3 小时前
Pi Agent——OpenClaw的大脑是怎么运转的
架构·openclaw
五度易链-区域产业数字化管理平台3 小时前
基于可信网络的产业链协同方案:五度易链架构解析
架构