微服务鉴权中心之网关配置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;
    }
}
相关推荐
O***p6045 小时前
前端的“复杂性红线”:如何在超大型应用时代构建可持续演进的前端架构?
前端·架构
狗哥哥5 小时前
🚀 拒绝重复造轮子!在 Vue3 项目中打造一套企业级“统一上传服务”(支持分片、秒传、断点续传)
vue.js·架构
min1811234567 小时前
分公司组织架构图在线设计 总部分支管理模板
大数据·人工智能·信息可视化·架构·流程图
码界奇点7 小时前
基于微服务架构的悟空人力资源管理系统设计与实现
spring cloud·微服务·云原生·架构·毕业设计·源代码管理
weixin_416660077 小时前
豆包与DeepSeek底层大模型的深度解析:技术架构、设计理念与生态分野
人工智能·ai·架构·deepseek
狗哥哥8 小时前
前端权限系统的“断舍离”:从安全防线到体验向导的架构演进
vue.js·架构
小安同学iter8 小时前
天机学堂-排行榜功能-day08(六)
java·redis·微服务·zset·排行榜·unlink·天机学堂
cike_y9 小时前
JavaBean&MVC三层架构
java·架构·mvc·javaweb·java开发
前端老宋Running11 小时前
别再写 API 路由了:Server Actions 才是全栈 React 的终极形态
前端·react.js·架构
前端老宋Running11 小时前
跟“白屏”说拜拜:用 Next.js 把 React 搬到服务器上,Google 爬虫都要喊一声“真香”
前端·react.js·架构