当前位置: 首页 > article >正文

通过springcloud gateway优雅的进行springcloud oauth2认证和权限控制

代码地址

如果对你有帮助请给个start,本项目会持续更新,目标是做一个可用的快速微服务开发平台,成为接私活,毕设的开发神器, 欢迎大神们多提意见和建议

使用的都是spring官方最新的版本,版本如下:

  <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.6.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

springcloud gateway进行token校验时使用框架封装好的,不在需要通过自定义过滤器进行认证
引入依赖:

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-resource-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>
    </dependencies>

修改配置文件

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          jwk-set-uri: http://localhost:8000/public/key.json

增加一个配置文件

package com.digierp.gateway.config;

import com.digierp.gateway.component.PermissionAuthorizationManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

/**
 * @author liuhao
 * @date 2020/4/10
 */
@EnableWebFluxSecurity
public class GateWayWebSecurityConfig {

    @Autowired
    private PermissionAuthorizationManager permissionAuthorizationManager;

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange()
                .pathMatchers("/security/**").permitAll()
                .anyExchange().access(permissionAuthorizationManager);

        http.oauth2ResourceServer().jwt();
        http.csrf().disable();
        return http.build();
    }

}

需要在网关做权限控制添加ReactiveAuthorizationManager<AuthorizationContext>接口的实现, 如果不需要,请忽略

package com.digierp.gateway.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author liuhao
 * @date 2020/4/11
 */
@Slf4j
@Component
public class PermissionAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    /**
     * 实现权限验证判断
     */
    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authenticationMono, AuthorizationContext authorizationContext) {
        ServerWebExchange exchange = authorizationContext.getExchange();
        //请求资源
        String requestPath = exchange.getRequest().getURI().getPath();
        return authenticationMono.map(auth -> {
            new AuthorizationDecision(checkAuthorities(exchange, auth, requestPath));
        }).defaultIfEmpty(new AuthorizationDecision(false));

    }
    //权限校验
    private boolean checkAuthorities(ServerWebExchange exchange, Authentication auth, String requestPath) {
        Jwt principal = (Jwt) auth.getPrincipal();
        log.info("访问的URL是:{}用户信息:{}",requestPath, principal.getClaims().get("user_name"));
        return RandomUtils.nextInt() % 2 == 0 ;
    }

}
image.png


喜欢的朋友记得点赞、收藏、关注哦!!!


http://www.kler.cn/news/312537.html

相关文章:

  • Python编码系列—Python代理模式:为对象赋予超能力的魔法
  • QTcpSocket和QLocalSocket详解
  • 【网络编程】socket套接字|sockaddr|sockaddr_in|通信过程
  • 《深度学习》—— 神经网络模型中的损失函数及正则化惩罚和梯度下降
  • 如何搭建虚拟机Ubuntu?
  • icpc江西:L. campus(dij最短路)
  • el-input 只能输入数字和一个小数点,或者只能输入两位小数
  • OpenHarmony(鸿蒙南向开发)——小型系统内核(LiteOS-A)【时间管理】
  • 探索自闭症寄宿学校的专属教育模式
  • java原子操作类
  • 基于LSTM的文本摘要生成实战教程
  • Python学习的主要知识框架
  • 同样实用的CSS剪裁属性clip-path
  • esp32-C2 对接火山引擎实现语音转文本(二)
  • Windows安装启动:stable-diffusion-webui,AIGC大模型文生图、文生视频,Python
  • 使用mlp算法对Digits数据集进行分类
  • 必应bing广告优势,国内开户注意事项备忘录
  • Windows系统 Bat命令生成快捷方式
  • LLM - 理解 多模态大语言模型(MLLM) 的 指令微调(Instruction-Tuning) 与相关技术 (四)
  • 【例题】lanqiao3225 宝藏排序Ⅰ
  • 2-100 基于matlab的水果识别
  • 【诉讼流程-健身房-违约-私教课-诉讼书提交流程-民事诉讼-自我学习-铺平通往法律的阶梯-讲解(3)】
  • spring MVC 拦截器
  • 本地git仓库配置远程仓库的地址
  • el-table的树形结构结合多选框使用,实现单选父子联动,全选,反选功能
  • SpringBoot结合Mybatis-plus项目直接执行sql语句
  • Vue学习记录之五(组件/生命周期)
  • IO流体系(FiletOutputStream)
  • Go Testify学习与使用
  • Linux环境变量进程地址空间