微服务网关的作用、创建微服务网关、网关跨域配置、网关过滤配置、令牌桶限流、Base64加密和解密、BCrypt加密和比对、JWT令牌、JWT工具类、网关权限认证

本文介绍了微服务网关的作用,如跨域配置、路由设置、限流策略等。通过创建微服务网关,包括添加依赖、配置YAML文件和启动类。还详细讲解了如何进行网关跨域配置、令牌桶限流的实现,以及Base64、BCrypt加密和JWT令牌的使用,包括JWT工具类的创建。最后讨论了网关权限认证,涉及用户登录功能和JWT令牌的验证过滤器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、微服务网关的作用

1、安全,提供了统一访问入口,降低了服务受攻击面积
2、提供了统一跨域解决方案
3、提供了统一日志记录操作,可以进行统一监控
4、提供了统一权限认证支持
5、提供了微服务限流功能,可以保护微服务,防止雪崩效应发生

二、创建微服务网关

1、shop-gateway 父工程,添加依赖

        <!--网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--eureka客户-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

2、创建 shop-geteway-web 工程,父工程为 shop-gateway

3、application.yml 配置

spring:
  application:
    name: gateway-web #网关名
server:
  port: 8001 # 网关端口

# eureka 服务地址
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:6868/eureka
  instance:
    prefer-ip-address: true
    
# 要进行远程访问,必须在应用程序属性中暴露HTTP或JMX 端口。
management:
  endpoint:
    gateway:
      enabled: true
    web:
      exposure:
        include: true

4、启动类

@SpringBootApplication
@EnableEurekaClient  //开启Eureka客户端
public class GateWayWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(GateWayWebApplication.class,args);
    }
}

三、网关跨域配置

有时候,我们需要对所有微服务跨域请求进行处理,则可以在gateway中进行跨域支持。修改application.yml,添加如下

     

四、路由配置

Host 路由,路径匹配过滤配置,PrefixPath 过滤配置,StripPrefix 过滤配置,LoadBalancerClient 路由过滤器(客户端负载均衡)

五、令牌桶限流

使用令牌桶算法(匀速生成令牌,存入令牌桶(Redis),用户访问,先从令牌桶获取令牌,在访问)

1、添加依赖

        <!--redis(使用令牌桶进行请求次数限流)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

2、定义KeyResolver

在Applicatioin引导类中添加如下代码,KeyResolver用于计算某一个类型的限流的KEY也就是说,可以通过KeyResolver来指定限流的Key。

我们可以根据IP来限流,比如每个IP每秒钟只能请求一次,在GatewayWebApplication定义key的获取,获取客户端IP,将IP作为key

    /**创建用户唯一标识,使用ip作为用户唯一标识,根据ip进行限流*/
    @Bean(name="ipKeyResolver")
    public KeyResolver userKeyResolver(){
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                String ip = exchange.getRequest().getRemoteAddress().getHostString();
                System.out.println("用户请求的ip"+ip);
                return Mono.just(ip);
            }
        };
    }

 3、修改application.yml中配置项,指定限制流量的配置以及REDIS的配置

      

      

六、Base64加密和解密

public class Base64Test {
    /*base64加密*/
    @Test
    public void testEncode() throws UnsupportedEncodingException {
        byte[] encode = Base64.getEncoder().encode("111111".getBytes());
        String encodeString=new String(encode,"UTF-8");
        System.out.println("加密后的密文:"+encodeString);
    }
    @Test
    public void testDecode() throws UnsupportedEncodingException {
        String encodeString="MTExMTEx";
        byte[] decodecode = Base64.getDecoder().decode(encodeString);
        String string=new String(decodecode,"UTF-8");
        System.out.println("解密后的密文:"+string);
    }

}

 七、BCrypt加密和比对

// Copyright (c) 2006 Damien Miller <[email protected]>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

package entity;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

/**
 * BCrypt implements OpenBSD-style Blowfish password hashing using
 * the scheme described in "A Future-Adaptable Password Scheme" by
 * Niels Provos and David Mazieres.
 * <p>
 * This password hashing system tries to thwart off-line password
 * cracking using a computationally-intensive hashing algorithm,
 * based on Bruce Schneier's Blowfish cipher. The work factor of
 * the algorithm is parameterised, so it can be increased as
 * computers get faster.
 * <p>
 * Usage is really simple. To hash a password for the first time,
 * call the hashpw method with a random salt, like this:
 * <p>
 * <code>
 * String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt()); <br />
 * </code>
 * <p>
 * To check whether a plaintext password matches one that has been
 * hashed previously, use the checkpw method:
 * <p>
 * <code>
 * if (BCrypt.checkpw(candidate_password, stored_hash))<br />
 * &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It matches");<br />
 * else<br />
 * &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It does not match");<br />
 * </code>
 * <p>
 * The gensalt() method takes an optional parameter (log_rounds)
 * that determines the computational complexity of the hashing:
 * <p>
 * <code>
 * String strong_salt = BCrypt.gensalt(10)<br />
 * String stronger_salt = BCrypt.gensalt(12)<br />
 * </code>
 * <p>
 * The amount of work increases exponentially (2**log_rounds), so 
 * each increment is twice as much work. The default log_rounds is
 * 10, and the valid range is 4 to 30.
 *
 * @version 0.2
 */
public class BCrypt {
	// BCrypt parameters
	private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
	private static final int BCRYPT_SALT_LEN = 16;

	// Blowfish parameters
	private static final int BLOWFISH_NUM_ROUNDS = 16;

	// Initial contents of key schedule
	private static final int P_orig[] = {
		0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
		0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
		0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
		0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
		0x9216d5d9, 0x8979fb1b
	};
	private static final int S_orig[] = {
		0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
		0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
		0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
		0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
		0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
		0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
		0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
		0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
		0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
		0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
		0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
		0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
		0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
		0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
		0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
		0x
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiz198183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值