国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】

這篇具有很好參考價(jià)值的文章主要介紹了SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

SpringCloud 大型系列課程正在制作中,歡迎大家關(guān)注與提意見。
程序員每天的CV 與 板磚,也要知其所以然,本系列課程可以幫助初學(xué)者學(xué)習(xí) SpringBooot 項(xiàng)目開發(fā) 與 SpringCloud 微服務(wù)系列項(xiàng)目開發(fā)

本文章是系列文章中的一篇

  • 1、SpringCloud 項(xiàng)目基礎(chǔ)工程搭建 【SpringCloud系列1】
  • 2、SpringCloud 集成Nacos注冊(cè)中心 【SpringCloud系列2】
  • 3、SpringCloud Feign遠(yuǎn)程調(diào)用 【SpringCloud系列3】
  • 4、SpringCloud Feign遠(yuǎn)程調(diào)用公共類抽取 【SpringCloud系列4】
  • 5、SpringCloud 整合Gateway服務(wù)網(wǎng)關(guān) 【SpringCloud系列5】
  • 6、SpringCloud 整合 Spring Security 認(rèn)證鑒權(quán)【SpringCloud系列6】

SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】
本文章實(shí)現(xiàn)的是 Gateway 網(wǎng)關(guān)中的令牌校驗(yàn)功能 ,上圖中所示用戶所有的訪問全部走網(wǎng)關(guān),然后在網(wǎng)關(guān)每次都調(diào)用 auth-api 鑒權(quán),當(dāng)訪問量足夠大的時(shí)候,還是會(huì)有訪問性能問題,所以優(yōu)化如下:
SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】

1 網(wǎng)關(guān)Gateway 添加 security 與 oauth2 相關(guān)配置

這里添加的 security 與 oauth2 相關(guān)配置 ,是為了解密 auth-api 中生成的 access_token 令牌信息

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>

然后添加安全攔截配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

/**
 * @description 安全配置類
 * @author 早起的年輕人
 */
 @EnableWebFluxSecurity
 @Configuration
 public class SecurityConfig {
  //安全攔截配置
  @Bean
  public SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) {

   return http.authorizeExchange()
           .pathMatchers("/**").permitAll()
           .anyExchange().authenticated()
           .and().csrf().disable().build();
  }
 }

配置 JwtAccessTokenConverter 所使用的密鑰信息

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @author 早起的年輕人
 * @version 1.0
 **/
@Configuration
public class TokenConfig {

    String SIGNING_KEY = "test_key";

    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(SIGNING_KEY);
        return converter;
    }

}

然后 網(wǎng)關(guān)配置文件中添加 auth-api 相關(guān)的路由

server:
  port: 10001
spring:
  application:
    name: '@project.name@'
  cloud:
    nacos:
      server-addr: localhost:8848 # nacos地址
    gateway:
      routes: # 網(wǎng)關(guān)路由配置
        - id: rewritepath_route
          uri: https://www.baidu.com/
          predicates:
            - Path=/search/**
          filters:
            - RewritePath=/search/(?<segment>.*), /$\{segment}

        - id: user-service # 路由id,自定義,只要唯一即可
          # uri: http://127.0.0.1:8081 # 路由的目標(biāo)地址 http就是固定地址
          uri: lb://user-service # 路由的目標(biāo)地址 lb就是負(fù)載均衡,后面跟服務(wù)名稱
          predicates: # 路由斷言,也就是判斷請(qǐng)求是否符合路由規(guī)則的條件
            - Path=/user/** # 這個(gè)是按照路徑匹配,只要以/user/開頭就符合要求
        - id: order-service # 路由id,自定義,只要唯一即可
          # uri: http://127.0.0.1:8081 # 路由的目標(biāo)地址 http就是固定地址
          uri: lb://order-service
          predicates:
            - Path=/order/**

        - id: auth-api # 路由id,自定義,只要唯一即可
          # uri: http://127.0.0.1:8081 # 路由的目標(biāo)地址 http就是固定地址
          uri: lb://auth-api
          predicates:
            - Path=/oauth/**
2 網(wǎng)關(guān)認(rèn)證過慮器
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
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.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author 早起的年輕輕人
 * @version 1.0
 * @description 網(wǎng)關(guān)認(rèn)證過慮器
 */
@Component
@Slf4j
public class GatewayAuthFilter implements GlobalFilter, Ordered {


    //白名單
    private static List<String> whitelist = null;

    static {
        //加載白名單
        try (
                InputStream resourceAsStream = GatewayAuthFilter.class.getResourceAsStream("/security-whitelist.properties");
        ) {
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            Set<String> strings = properties.stringPropertyNames();
            whitelist= new ArrayList<>(strings);

        } catch (Exception e) {
            whitelist = new ArrayList<>();
            log.error("加載/security-whitelist.properties出錯(cuò):{}",e.getMessage());
            e.printStackTrace();
        }


    }

    @Autowired
    private TokenStore tokenStore;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //請(qǐng)求的url
        String requestUrl = exchange.getRequest().getPath().value();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        //白名單放行
        for (String url : whitelist) {
            if (pathMatcher.match(url, requestUrl)) {
                return chain.filter(exchange);
            }
        }
        //檢查token是否存在
        String token = getToken(exchange);
        if (StringUtils.isBlank(token)) {
            return buildReturnMono("沒有認(rèn)證",exchange);
        }
        //判斷是否是有效的token
        OAuth2AccessToken oAuth2AccessToken;
        try {
            oAuth2AccessToken = tokenStore.readAccessToken(token);

            boolean expired = oAuth2AccessToken.isExpired();
            if (expired) {
                return buildReturnMono("認(rèn)證令牌已過期",exchange);
            }
            return chain.filter(exchange);
        } catch (InvalidTokenException e) {
            log.info("認(rèn)證令牌無效: {}", token);
            return buildReturnMono("認(rèn)證令牌無效",exchange);
        }

    }

    /**
     * 獲取token
     */
    private String getToken(ServerWebExchange exchange) {
        String tokenStr = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StringUtils.isBlank(tokenStr)) {
            return null;
        }
        return tokenStr;
    }




    private Mono<Void> buildReturnMono(String error, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        Map<String,Object> map = new HashMap<>();
        map.put("code",403);
        map.put("message",error);

        String jsonString = JSON.toJSONString(map);
        byte[] bits = jsonString.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}

Spring Cloud Gateway 根據(jù)作用范圍劃分為 GatewayFilter 和 GlobalFilter

  • GatewayFilter : 需要通過spring.cloud.routes.filters 配置在具體路由下,只作用在當(dāng)前路由上或通過spring.cloud.default-filters配置在全局,作用在所有路由上。
  • GlobalFilter : 不需要在配置文件中配置,作用在所有的路由上,最終通過GatewayFilterAdapter包裝成GatewayFilterChain可識(shí)別的過濾器
3 啟動(dòng)服務(wù) 測(cè)試

SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】
首先通過網(wǎng)關(guān)訪問訂單詳情

http://localhost:10001/order/109

使用很久之前的一個(gè)token
SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】
然后再通過網(wǎng)關(guān)獲取令牌
SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】
然后使用新獲取到的令牌來訪問訂單詳情
SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】

4 獲取token中的用戶信息

在網(wǎng)關(guān)中將token解析,獲取登錄 token 中對(duì)應(yīng)的用戶 userId , 在網(wǎng)關(guān)中的令牌校驗(yàn)過濾器 GatewayAuthFilter 中添加內(nèi)容:

public class GatewayAuthFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        
        ... ... 
            //----------獲取token中的用戶令牌--------------------------------------------------------------------
            OAuth2Authentication authentication = tokenStore.readAuthentication(token);
            User authUser = (User) authentication.getPrincipal();
            //獲取保存的用戶令牌 我這里是一個(gè)JSON 
            String username = authUser.getUsername();
            //使用Fastjson 將json字符串轉(zhuǎn)為map
            Map<String, Object> parse = JSON.parseObject(username, Map.class);
            //獲取其中的 userId
            String userId = parse.get("userId").toString();

            ServerHttpRequest req = exchange.getRequest();
            HttpHeaders httpHeaders = req.getHeaders();
            ServerHttpRequest.Builder requestBuilder = req.mutate();
            // 先刪除,后新增
            //requestBuilder.headers(k -> k.remove("要修改的header的key"));
            // requestBuilder.header("要修改的header的key", 處理完之后的header的值);

            // 或者直接修改,要求修改的變量為final
            requestBuilder.headers(k -> k.set("userId", userId));
            log.info("令牌解析成功:userId is {}",userId);

            ServerHttpRequest request = requestBuilder.build();
            exchange.mutate().request(request).build();

            return chain.filter(exchange);
        } catch (InvalidTokenException e) {
            log.info("認(rèn)證令牌無效: {}", token);
            return buildReturnMono("認(rèn)證令牌無效", exchange);
        }
    }
}

這里是獲取了用戶的 userId ,然后將userId添加到請(qǐng)求頭中,比如在后續(xù)的 admin 管理后臺(tái)的服務(wù)中,可以直接通過 @RequestHeader 獲取
SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】

到此 網(wǎng)關(guān)中的鑒權(quán)功能開發(fā)完成。

本項(xiàng)目源碼 https://gitee.com/android.long/spring-cloud-biglead/tree/master/biglead-api-07-auth
如果有興趣可以關(guān)注一下公眾號(hào) biglead ,每周都會(huì)有 java、Flutter、小程序、js 、英語相關(guān)的內(nèi)容分享文章來源地址http://www.zghlxwxcb.cn/news/detail-483242.html

到了這里,關(guān)于SpringCloud網(wǎng)關(guān)Gateway認(rèn)證鑒權(quán)【SpringCloud系列7】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • satoken+ gateway網(wǎng)關(guān)統(tǒng)一鑒權(quán) 初版

    satoken+ gateway網(wǎng)關(guān)統(tǒng)一鑒權(quán) 初版

    本博客內(nèi)容 參考了satoken官網(wǎng)實(shí)現(xiàn),satoken官網(wǎng)地址: https://sa-token.cc/doc.html#/micro/gateway-auth jinyi-gateway 網(wǎng)關(guān)服務(wù) jinyi-user-service 用戶服務(wù) 2.1 jinyi-user-api 2.2 jinyi-user-client 2.3 jinyi-user-provider jinyi-common 通用服務(wù),定義了一些統(tǒng)一返回類,全局常量(R等) 項(xiàng)目層級(jí)關(guān)系截圖: 3.1jinyi-

    2023年04月20日
    瀏覽(19)
  • springcloud-gateway-2-鑒權(quán)

    springcloud-gateway-2-鑒權(quán)

    目錄 一、跨域安全設(shè)置 二、GlobalFilter實(shí)現(xiàn)全局的過濾與攔截。 三、GatewayFilter單個(gè)服務(wù)過濾器 1、原理-官方內(nèi)置過濾器 2、自定義過濾器-TokenAuthGatewayFilterFactory 3、完善TokenAuthGatewayFilterFactory的功能 4、每一個(gè)服務(wù)編寫一個(gè)或多個(gè)過濾器,實(shí)現(xiàn)鑒權(quán)的需要 四、總結(jié) 續(xù)前篇,介

    2024年02月03日
    瀏覽(22)
  • Spring Gateway + Oauth2 + Jwt網(wǎng)關(guān)統(tǒng)一鑒權(quán)

    Spring Gateway + Oauth2 + Jwt網(wǎng)關(guān)統(tǒng)一鑒權(quán)

    之前文章里說過,分布式系統(tǒng)的鑒權(quán)有兩種方式,一是在網(wǎng)關(guān)進(jìn)行統(tǒng)一的鑒權(quán)操作,二是在各個(gè)微服務(wù)里單獨(dú)鑒權(quán)。 第二種方式比較常見,代碼網(wǎng)上也是很多。今天主要是說第一種方式。 重要前提:需要收集各個(gè)接口的uri路徑和所需權(quán)限列表的對(duì)應(yīng)關(guān)系,并存入緩存。 服務(wù)

    2024年02月03日
    瀏覽(24)
  • 【實(shí)現(xiàn)微服務(wù)集成satoken在網(wǎng)關(guān)gateway處統(tǒng)一鑒權(quán)】

    【實(shí)現(xiàn)微服務(wù)集成satoken在網(wǎng)關(guān)gateway處統(tǒng)一鑒權(quán)】

    本文旨在使用開源輕量級(jí) Java 權(quán)限認(rèn)證框架sa-token+springcloud-gateway實(shí)現(xiàn)微服務(wù)在網(wǎng)關(guān)處統(tǒng)一鑒權(quán)。sa-token參考地址:https://sa-token.cc/doc.html#/ 項(xiàng)目按照業(yè)務(wù)分為三個(gè)板塊,如圖: api(也就是微服務(wù)中各種api接口,不涉及任何權(quán)限相關(guān)代碼,只提供服務(wù)) auth(認(rèn)證中心,實(shí)現(xiàn)登陸邏輯

    2024年02月10日
    瀏覽(18)
  • GateWay網(wǎng)關(guān)自定義過濾器實(shí)現(xiàn)token校驗(yàn)完成統(tǒng)一鑒權(quán)

    GateWay網(wǎng)關(guān)自定義過濾器實(shí)現(xiàn)token校驗(yàn)完成統(tǒng)一鑒權(quán)

    gateWay---API網(wǎng)關(guān),也可以稱為業(yè)務(wù)網(wǎng)關(guān),主要服務(wù)于微服務(wù)的; (1)? 三大組件 路由(Route) ????????構(gòu)建網(wǎng)關(guān)的基本模塊,由id(唯一標(biāo)示)、目標(biāo)URI、一組斷言、一組過濾器組成,如果斷言為true,則匹配該路由 ? 斷言(Predicate) ? ? ? ? ?可以使用它匹配來自HTTP請(qǐng)求的任何

    2024年02月08日
    瀏覽(23)
  • SpringCloud搭建微服務(wù)之Gateway+Jwt實(shí)現(xiàn)統(tǒng)一鑒權(quán)

    SpringCloud搭建微服務(wù)之Gateway+Jwt實(shí)現(xiàn)統(tǒng)一鑒權(quán)

    在微服務(wù)項(xiàng)目中,需要對(duì)整個(gè)微服務(wù)系統(tǒng)進(jìn)行權(quán)限校驗(yàn),通常有兩種方案,其一是每個(gè)微服務(wù)各自鑒權(quán),其二是在網(wǎng)關(guān)統(tǒng)一鑒權(quán),第二種方案只需要一次鑒權(quán)就行,避免了每個(gè)微服務(wù)重復(fù)鑒權(quán)的麻煩,本文以網(wǎng)關(guān)統(tǒng)一鑒權(quán)為例介紹如何搭建微服務(wù)鑒權(quán)項(xiàng)目。 本文案例中共有四

    2024年02月13日
    瀏覽(23)
  • SpringCloud-網(wǎng)關(guān) Gateway

    SpringCloud-網(wǎng)關(guān) Gateway

    ??官方地址:SpringCloud Gateway ??網(wǎng)關(guān)統(tǒng)一了服務(wù)的入口,可以方便實(shí)現(xiàn)對(duì)眾多服務(wù)接口進(jìn)行管控,對(duì)訪問服務(wù)的身份認(rèn)證,防報(bào)文重放與防數(shù)據(jù)篡改,功能調(diào)用的業(yè)務(wù)鑒權(quán),響應(yīng)數(shù)據(jù)的脫敏,流量與并發(fā)控制,甚至基于API調(diào)用的計(jì)量或者計(jì)費(fèi)等等。更通俗理解,網(wǎng)關(guān)可以

    2024年02月04日
    瀏覽(23)
  • SpringCloud:Gateway服務(wù)網(wǎng)關(guān)

    SpringCloud:Gateway服務(wù)網(wǎng)關(guān)

    網(wǎng)關(guān)(Gateway)是將兩個(gè)使用不同協(xié)議的網(wǎng)絡(luò)段連接在一起的設(shè)備。 網(wǎng)關(guān)的作用就是對(duì)兩個(gè)網(wǎng)絡(luò)段中的使用不同傳輸協(xié)議的數(shù)據(jù)進(jìn)行互相的翻譯轉(zhuǎn)換。 創(chuàng)建服務(wù) 導(dǎo)入依賴 編寫啟動(dòng)類 添加配置 Route Predicate Factories :: Spring Cloud Gateway 對(duì)所有路徑都生效 全局過濾器的作用也是處理

    2024年02月01日
    瀏覽(27)
  • springcloud-網(wǎng)關(guān)(gateway)

    springcloud-網(wǎng)關(guān)(gateway)

    Spring Cloud Gateway旨在提供一種簡(jiǎn)單而有效的方式來路由到API,并為其提供跨領(lǐng)域的關(guān)注,如:安全、監(jiān)控/指標(biāo)和容錯(cuò) Route(路由) : 網(wǎng)關(guān)的基本構(gòu)件。它由一個(gè) ID 、一個(gè)目的地 URI 、一個(gè)謂詞( Predicate )集合和一個(gè)過濾器( Filter )集合定義。如果集合謂詞為真,則路由被

    2024年02月21日
    瀏覽(16)
  • springcloud(gateway網(wǎng)關(guān))

    springcloud(gateway網(wǎng)關(guān))

    目錄 1. gateway簡(jiǎn)介 1.1 是什么 1.2 作用 1.3 主要特征 1.4 與zuul的主要區(qū)別 1.5 主要組件 1.6 架構(gòu)圖 2. 開發(fā)示例 2.1 創(chuàng)建一個(gè)gateway模塊 2.2 與nacos結(jié)合使用 2.2.1 默認(rèn)規(guī)則 2.2.2 通過配置文件配置路由 2.2.3 動(dòng)態(tài)路由 SpringCloud Gateway 作為 Spring Cloud 生態(tài)系統(tǒng)中的網(wǎng)關(guān),目標(biāo)是替代 Zuul,在

    2024年02月07日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包