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

这篇具有很好参考价值的文章主要介绍了微服务鉴权中心之网关配置SpringSecurity+oauth2。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

微服务鉴权中心之网关配置SpringSecurity+oauth2,精通spring系列,微服务,架构

1. 网关配置oauth2之TokenStore存储方式,此处用RedisTokenStore

@Configuration

public class TokenConfig {

    @Autowired

    private RedisConnectionFactory redisConnectionFactory;

    @Bean

    public TokenStore tokenStore() {

        return new RedisTokenStore(redisConnectionFactory);

    }

 }

2.网关配置security

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

3.网关拦截token文章来源地址https://www.toymoban.com/news/detail-634551.html

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;
    }
}

到了这里,关于微服务鉴权中心之网关配置SpringSecurity+oauth2的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringSecurity学习(八)OAuth2.0、授权服务器、资源服务器、JWT令牌的使用

    OAuth2是一个认证协议,SpringSecurity对OAuth2协议提供了响应的支持,开发者可以非常方便的使用OAuth2协议。 简介 四种授权模式 Spring Security OAuth2 GitHub授权登录 授权服务器与资源服务器 使用JWT OAuth是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密资源

    2024年02月02日
    浏览(46)
  • SpringSecurity+OAuth2.0

    OAuth(Open Authorization)是一个关于授权(authorization)的开放网络标准,允许用户授权第三方应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容。OAuth 在全世界得到广泛应用,目前的版本是 2.0 版。 简单

    2024年02月13日
    浏览(31)
  • SpringSecurity+Oauth2+JWT

    快速入门 1. 创建基础项目 file == new == project == Spring Initializr ==next == web(Spring Web)、Security(Spring Security) ==一直下一步 2. 编写代码进行测试 创建controller static下创建login.html、main.html 3. 启动项目进行测试 访问http://localhost:8080/login.html 会进入SpringSecurity框架自带的登入页面 用户默认

    2024年02月12日
    浏览(30)
  • SpringSecurity之Oauth2介绍

    第三方认证技术方案最主要是解决 认证协议的通用标准问题 ,因为要实现跨系统认证,各系统之间要遵循一定的接口协议。 OAUTH协议为用户资源的授权提供了一个安全的、开放而又简易的标准。同时,任何第三方都可以使用OAUTH认证服务,任何服务提供商都可以实现自身的

    2023年04月09日
    浏览(33)
  • SpringSecurity +oauth2获取当前登录用户(二)

    特别注意:以下内容如果访问失败或有其他疑问,可先学习: SpringSecurity +oauth2+JWT实现统一授权和认证及项目搭建(一) 1 获取当前用户的信息代码为: 但是,通过运行会发现principal的值只是 用户名 ,没有用户信息,通过去看源码,才发现问题所在,以下是源码: 源码类:

    2023年04月12日
    浏览(30)
  • SpringSecurity+ Oauth2.0+JWT 0-1

    AuthorizationServer 需要继承AuthorizationServerConfigurerAdapter AuthorizationServerConfigurerAdapter源码 AuthorizationServerSecurityConfigurer:配置令牌端点(Token Endpoint)的安全约束 ClientDetailsServiceConfigurer:配置OAuth2客户端 AuthorizationServerEndpointsConfigurer:配置授权(authorization)以及令牌(token)的访

    2024年02月07日
    浏览(33)
  • springboot整合springsecurity+oauth2.0密码授权模式

    本文采用的springboot去整合springsecurity,采用oauth2.0授权认证,使用jwt对token增强。本文仅为学习记录,如有不足多谢提出。 OAuth 2.0是用于授权的行业标准协议。OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等。 Resource owner(资源拥有者)

    2024年02月04日
    浏览(45)
  • 权限管理 springboot集成springSecurity Oauth2 JWT

    目录 一、SpringSeurity的基础操作 1、引入主要依赖 2、加密器 3、实现自定义登录逻辑 4、访问限制 5、自定义异常处理  6、通过注解的方式配置访问控制 二、Auth2认证方案 1、什么是Auth2认证 2、Oauth2最常用的授权模式  3、依赖引入 4、添加配置类 5、测试 6、存在到Redis里,后续

    2023年04月14日
    浏览(33)
  • 五、SpringSecurity OAuth2扩展手机验证码授权模式

    代码仓库:地址 代码分支:lesson5 在上一篇文章中,我们使用SpringSecurity OAuth2搭建了一套授权服务,对业务系统进行统一授权管理。OAuth提供了四种授权方式: 授权码模式(authorization_code) 简化模式(implicit) 客户端(client_credentials) 密码(password) 在实际业务中上述四种模式不

    2024年02月11日
    浏览(43)
  • SpringSecurity:OAuth2 Client 结合GitHub授权案例(特简单版)

    本随笔说明:这仅作为OAuth2 Client初次使用的案例,所以写得很简单,有许多的不足之处。 OAuth2 Client(OAuth2客户端)是指使用OAuth2协议与授权服务器进行通信并获取访问令牌的应用程序或服务。OAuth2客户端代表最终用户(资源拥有者)向授权服务器请求授权,并使用授权后的

    2024年02月03日
    浏览(85)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包