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

SpringCloud Gateway + Security + JWT 最快速的集成

這篇具有很好參考價(jià)值的文章主要介紹了SpringCloud Gateway + Security + JWT 最快速的集成。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

版本

Springboot版本采用的是最新的:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.9</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

網(wǎng)關(guān)主要采用的是:文章來源地址http://www.zghlxwxcb.cn/news/detail-594749.html

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

核心SecurityConfig配置

@EnableWebFluxSecurity
public class SecurityConfig {
    @Autowired
    PermitUrlConfig permitUrlConfig;

    @Autowired
    DefaultSecurityContext defaultSecurityContext;

    @Autowired
    DefaultAuthManager defaultAuthManager;

    @Autowired
    DefaultAccessDecision defaultAccessDecision;

    @Autowired
    DefaultAccessDenied defaultAccessDenied;

    /**
     * 訪問權(quán)限授權(quán)
     *
     * @param http
     * @return
     */
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
                .csrf().disable()
                .securityContextRepository(defaultSecurityContext)              //認(rèn)證啟動(dòng)
                .authenticationManager(defaultAuthManager)                      //認(rèn)證管理
                .authorizeExchange(exchange -> exchange                         //請(qǐng)求攔截處理
                        .pathMatchers(permitUrlConfig.permit()).permitAll()     //默認(rèn)放開的地址
                        .pathMatchers(HttpMethod.OPTIONS).permitAll()           //放開的請(qǐng)求方法
                        .anyExchange().access(defaultAccessDecision)            //其他的地址走后續(xù)驗(yàn)證
                )
                .exceptionHandling().accessDeniedHandler(defaultAccessDenied);  //訪問拒絕后執(zhí)行的處理

        return http.build();
    }
}

定義放開配置的URL

@Component
public class PermitUrlConfig {
    public static final String CONTEXT_PATH = "/gateway";

    /**
     * 需要訪問的url
     */
    private String[] permitUrl = {
            "/actuator/**",
            "/api-account/account/**"
    };

    private String[] heartbeatUrl = {
            "/heartbeat/**",
    };

    /**
     * 額外放開權(quán)限的url
     *
     * @param urls 自定義的url
     * @return 自定義的url和監(jiān)控中心需要訪問的url集合
     */
    public String[] permit(String... urls) {
        Set<String> set = new HashSet<>();
        if (urls.length > 0) {
            Collections.addAll(set, addContextPath(urls));
        }

        //放開權(quán)限的地址
        Collections.addAll(set, addContextPath(permitUrl));
        Collections.addAll(set, heartbeatUrl);

        return set.toArray(new String[set.size()]);
    }

    /**
     * 地址加訪問前綴
     * @param urls
     * @return
     */
    private String[] addContextPath(String[] urls) {
        for (int i = 0; i < urls.length; i++) {
            urls[i] = CONTEXT_PATH + urls[i];
        }

        return urls;
    }
}

核心配置中的處理器

DefaultSecurityContext啟動(dòng)認(rèn)證

@Component
public class DefaultSecurityContext implements ServerSecurityContextRepository {
    @Autowired
    DefaultAuthManager defaultAuthManager;

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return Mono.empty();
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String authorization = request.getHeaders().getFirst("Authorization");

        //調(diào)用defaultAuthManager的方法
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authorization, null);
        Mono<Authentication> authenticationMono = defaultAuthManager.authenticate(authenticationToken);

        return authenticationMono.map(SecurityContextImpl::new);
    }
}

DefaultAuthManager執(zhí)行認(rèn)證核心方法

@Slf4j
@Component
public class DefaultAuthManager implements ReactiveAuthenticationManager {
    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        String tokenString = (String) authentication.getPrincipal();
        String jwtToken = getJwtToken(tokenString);
        Map<String, Object> authResult = parseToken(jwtToken);

        return Mono.just(authentication).map(auth -> new UsernamePasswordAuthenticationToken(authResult, null, null));
    }

    /**
     * 讀取Jwt Token
     *
     * @param authorization
     * @return
     */
    private String getJwtToken(String authorization) {
        if (!StringUtils.hasText(authorization)) {
            return null;
        }

        boolean valid = authorization.startsWith("Bearer ");
        if (!valid) {
            return null;
        }

        return authorization.replace("Bearer ", "");
    }

    /**
     * 校驗(yàn)token
     *
     * @param jwtToken
     * @return
     */
    private Map<String, Object> parseToken(String jwtToken) {
        log.info("[gateway] jwtToken = {}", jwtToken);

        //認(rèn)證成功
        boolean verify = JwtUtils.verify(jwtToken);
        if (verify) {
            Map<String, Claim> claimMap = JwtUtils.decode(jwtToken);
            Claim claim = claimMap.getOrDefault("data", null);
            if (Objects.nonNull(claim)) {
                return claim.asMap();
            }
        }

        return null;
    }
}

DefaultAccessDecision判斷認(rèn)證后是否放行

@Component
public class DefaultAccessDecision implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext object) {
        Mono<AuthorizationDecision> mono = authentication.map(auth -> {
            Object authResult = auth.getPrincipal();

            //數(shù)據(jù)讀取非空,說明前期在auth的時(shí)候,jwt認(rèn)證返回非空
            if (Objects.nonNull(authResult)) {
                return new AuthorizationDecision(true);
            }

            return new AuthorizationDecision(false);
        });

        return mono;
    }
}

DefaultAccessDenied處理不放行的返回

@Slf4j
@Component
public class DefaultAccessDenied implements ServerAccessDeniedHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().add("Content-Type", "application/json; charset=UTF-8");

        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("message", "未授權(quán)禁止訪問");
        map.put("data", "請(qǐng)檢查Token是否合法");
        log.error("[DefaultAccessDenied] access forbidden path={}", exchange.getRequest().getPath());

        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        return response.writeWith(Mono.just(dataBuffer));
    }
}

到了這里,關(guān)于SpringCloud Gateway + Security + JWT 最快速的集成的文章就介紹完了。如果您還想了解更多內(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)文章

  • 微服務(wù)多模塊:Springboot+Security+Redis+Gateway+OpenFeign+Nacos+JWT (附源碼)僅需一招,520徹底拿捏你

    微服務(wù)多模塊:Springboot+Security+Redis+Gateway+OpenFeign+Nacos+JWT (附源碼)僅需一招,520徹底拿捏你

    ??可能有些人會(huì)覺得這篇似曾相識(shí),沒錯(cuò),這篇是由原文章進(jìn)行二次開發(fā)的。 前陣子有些事情,但最近看到評(píng)論區(qū)說原文章最后實(shí)現(xiàn)的是單模塊的驗(yàn)證,由于過去太久也懶得驗(yàn)證,所以重新寫了一個(gè)完整的可以跑得動(dòng)的一個(gè)。 OK,回到正題,以下是真正對(duì)應(yīng)的微服務(wù)多模塊

    2024年02月05日
    瀏覽(22)
  • SpringCloud Sentinel集成Gateway和實(shí)時(shí)監(jiān)控

    SpringCloud Sentinel集成Gateway和實(shí)時(shí)監(jiān)控

    想學(xué)習(xí)架構(gòu)師構(gòu)建流程請(qǐng)?zhí)D(zhuǎn):Java架構(gòu)師系統(tǒng)架構(gòu)設(shè)計(jì) 參看: https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81#spring-cloud-gateway 我們的項(xiàng)目流量入口是 SpringCloud Gateway ,因此我們重點(diǎn)講解Sentinel集成 Gateway 。 Sentinel 支持對(duì) Spring Cloud Gateway、Zuul 等主流的 API Gateway 進(jìn)

    2024年02月09日
    瀏覽(27)
  • SpringCloud nacos 集成 gateway ,實(shí)現(xiàn)動(dòng)態(tài)路由

    SpringCloud nacos 集成 gateway ,實(shí)現(xiàn)動(dòng)態(tài)路由

    ?? 作者: Linux猿 ?? 簡(jiǎn)介: CSDN博客專家??,華為云享專家??,Linux、C/C++、云計(jì)算、物聯(lián)網(wǎng)、面試、刷題、算法盡管咨詢我,關(guān)注我,有問題私聊! ?? 歡迎小伙伴們點(diǎn)贊??、收藏?、留言?? 目錄 一、準(zhǔn)備工作 1.1 下載代碼 1.2 運(yùn)行代碼 二、集成 gateway 2.1 修改 pom.xml 2

    2024年02月16日
    瀏覽(23)
  • Spring Gateway使用JWT實(shí)現(xiàn)統(tǒng)一身份認(rèn)證

    Spring Gateway使用JWT實(shí)現(xiàn)統(tǒng)一身份認(rèn)證

    在開發(fā)集群式或分布式服務(wù)時(shí),鑒權(quán)是最重要的一步,為了方便對(duì)請(qǐng)求統(tǒng)一鑒權(quán),一般都是會(huì)放在網(wǎng)關(guān)中進(jìn)行處理。目前非常流行的一種方案是使用JWT,詳細(xì)的使用說明,可以找相關(guān)的資料查閱,這里先不進(jìn)行深入的引用了。主要使用它下面的特性: 它的數(shù)據(jù)使用JSON格式封

    2024年02月12日
    瀏覽(18)
  • 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)
  • Gateway中Spring Security6統(tǒng)一處理CORS

    使用了 gateway 微服務(wù)作為整體的網(wǎng)關(guān),并且整合了 Spring Security6 ;還有一個(gè)system微服務(wù),作為被請(qǐng)求的資源,當(dāng)瀏覽器向 gateway 發(fā)送請(qǐng)求,請(qǐng)求 system 資源時(shí),遇到 CORS 問題。 于是我在 system 對(duì)應(yīng)的 controller 上加了 @CrossOrigin ,無效;配置 WebMvcConfigurer ,也無效。 后來發(fā)現(xiàn),

    2024年02月20日
    瀏覽(20)
  • springcloud-gateway集成knife4j

    springcloud-gateway集成knife4j

    springcloud-gateway集成knife4j(swagger2) 環(huán)境信息 準(zhǔn)備工作 微服務(wù)集成knife4j 第一步:編寫Knife4jApiInfoProperties 第二步:編寫配置類Knife4jConfig 第三步:放行相關(guān)資源 保證啟動(dòng)了knife4j 網(wǎng)關(guān)集成knife4j 編寫配置類Knife4jGatewayConfig 測(cè)試驗(yàn)證 相關(guān)資料 spring-boot:2.6.3 spring-cloud-alibaba:2

    2023年04月09日
    瀏覽(22)
  • 基于SpringCloud + Oauth2.0 + ShiroRedis + JWT + Gateway + Nacos + Nginx + Vue實(shí)現(xiàn)的SaaS數(shù)字商城系統(tǒng)

    基于SpringCloud + Oauth2.0 + ShiroRedis + JWT + Gateway + Nacos + Nginx + Vue實(shí)現(xiàn)的SaaS數(shù)字商城系統(tǒng)

    SaaS的英文全稱是Software as a Service,意思是軟件即服務(wù) ,是云計(jì)算的其中一種服務(wù)模式 SaaS是一種通過Internet提供集中托管應(yīng)用程序的方式,企業(yè)用戶一般通過客戶端或網(wǎng)頁來使用,無需購買、安裝或維護(hù)任何軟件及硬件,因此 SaaS應(yīng)用程序又被稱為\\\"基于Web的軟件\\\" 或 \\\"托管軟件

    2024年01月20日
    瀏覽(24)
  • 【SpringCloud】微服務(wù)技術(shù)棧入門3 - Gateway快速上手

    【SpringCloud】微服務(wù)技術(shù)棧入門3 - Gateway快速上手

    WebFlux gateway 基于 webflux 構(gòu)建 WebFlux 是基于反應(yīng)式流概念的響應(yīng)式編程框架,用于構(gòu)建異步非阻塞的 Web 應(yīng)用程序。它支持響應(yīng)式編程范式,并提供了一種響應(yīng)式的方式來處理 Web 請(qǐng)求。 與傳統(tǒng)的 Servlet API 相比,WebFlux 采用了基于事件驅(qū)動(dòng)的編程模型,不依賴于傳統(tǒng)的線程池模

    2024年02月07日
    瀏覽(56)
  • 微服務(wù)動(dòng)態(tài)權(quán)限管理方案(Spring Cloud Gateway+Spring Cloud Security)

    微服務(wù)動(dòng)態(tài)權(quán)限管理方案(Spring Cloud Gateway+Spring Cloud Security)

    微服務(wù)認(rèn)證方案的大體方向是統(tǒng)一在網(wǎng)關(guān)層面認(rèn)證鑒權(quán),微服務(wù)只負(fù)責(zé)業(yè)務(wù),和鑒權(quán)完全隔離 整體包含以下四個(gè)角色 客戶端 :需要訪問微服務(wù)資源 網(wǎng)關(guān) :負(fù)責(zé)轉(zhuǎn)發(fā)、認(rèn)證、鑒權(quán) OAuth2.0授權(quán)服務(wù) :負(fù)責(zé)認(rèn)證授權(quán)頒發(fā)令牌 微服務(wù)集合 :提供資源的一系列服務(wù)。 這里的客戶端

    2024年02月12日
    瀏覽(21)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

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

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包