一灰灰blog 一灰灰blog
首页
  • InfluxDB
  • MongoDB
  • MySql
  • 基础系列
  • DB系列
  • 搜索系列
  • MQ系列
  • WEB系列
  • 中间件
  • 运维
  • SpringSecurity
  • SpringCloud
  • QuickAlarm
  • QuickCrawer
  • QuickFix
  • QuickMedia
  • QuickSpi
  • QuickTask
  • 高可用
  • 分类
  • 标签
  • 归档
  • 收藏
  • 关于
GitHub (opens new window)

一灰灰blog

资深搬运工
首页
  • InfluxDB
  • MongoDB
  • MySql
  • 基础系列
  • DB系列
  • 搜索系列
  • MQ系列
  • WEB系列
  • 中间件
  • 运维
  • SpringSecurity
  • SpringCloud
  • QuickAlarm
  • QuickCrawer
  • QuickFix
  • QuickMedia
  • QuickSpi
  • QuickTask
  • 高可用
  • 分类
  • 标签
  • 归档
  • 收藏
  • 关于
GitHub (opens new window)
  • 基础系列

  • DB系列

  • 搜索系列

  • MQ系列

  • WEB系列

    • Request

    • Response

    • RestTemplate

    • WebClient

      • 【WEB系列】WebClient之基础使用姿势
      • 【WEB系列】WebClient之文件上传
      • 【WEB系列】WebClient之请求头设置
      • 【WEB系列】WebClient之Basic Auth授权
        • I. 项目环境
          • 1. 依赖
          • 2. REST接口
        • II. Basic Auth鉴权
          • 1. 设置请求头
          • 2. filter方式
          • 3. 测试与小结
        • II. 其他
          • 0. 项目
          • 1. 一灰灰Blog
      • 【WEB系列】WebClient之超时设置
      • 【WEB系列】WebClient之retrieve与exchange的使用区别介绍
      • 【WEB系列】WebClient之非200状态码信息捕获
      • 【WEB系列】WebClient之策略设置
      • 【WEB系列】WebClient之同步与异步
    • WebFlux

    • WebSocket

    • Web三剑客

    • 实例

    • 其他

  • 中间件

  • 运维

  • SpringSecurity

  • SpringCloud

  • Spring系列
  • WEB系列
  • WebClient
一灰灰
2020-07-16

【WEB系列】WebClient之Basic Auth授权

关于BasicAuth是什么,以及如何实现鉴权的知识点可以在之前的博文 【WEB系列】RestTemplate之Basic Auth授权 (opens new window) 中已经介绍过了,因此本篇将直接进入正文,介绍一下如何在WebClient中进行Basic Auth授权

# I. 项目环境

本项目借助SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA进行开发

# 1. 依赖

使用WebClient,最主要的引入依赖如下(省略掉了SpringBoot的相关依赖,如对于如何创建SpringBoot项目不太清楚的小伙伴,可以关注一下我之前的博文)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
1
2
3
4

# 2. REST接口

基于WebFlux提供一个http接口,根据请求头解析Basic Auth是否合法,一个最原始的简单实现方式如下

@GetMapping(path = "auth")
public Mono<String> auth(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
    List<String> authList = request.getHeaders().get("Authorization");
    if (CollectionUtils.isEmpty(authList)) {
        response.setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
        return Mono.just("no auth info!");
    }

    String auth = authList.get(0);
    String[] userAndPass = new String(new BASE64Decoder().decodeBuffer(auth.split(" ")[1])).split(":");
    if (userAndPass.length < 2) {
        response.setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
        return Mono.just("illegal auth info!");
    }

    if (!("user".equalsIgnoreCase(userAndPass[0]) && "pwd".equalsIgnoreCase(userAndPass[1]))) {
        response.setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
        return Mono.just("error auth info!");
    }


    return Mono.just("auth success: " + JSONObject.toJSONString(request.getQueryParams()));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

当鉴权成功之后,正常返回;当鉴权失败之后,返回403状态码,并返回对应的提示信息

# II. Basic Auth鉴权

理解Basic Auth实现原理的小伙伴,可以很简单的实现,比如直接设置请求头

# 1. 设置请求头

直接在WebClient创建的时候,指定默认的请求头即可

// 最原始的请求头设置方式
WebClient webClient = WebClient.builder()
        .defaultHeader("Authorization", "Basic " + Base64Utils.encodeToString("user:pwd".getBytes()))
        .baseUrl("http://127.0.0.1:8080").build();
Mono<ResponseEntity<String>> response =
        webClient.get().uri("/auth?name=一灰灰&age=18").exchange().flatMap(s -> s.toEntity(String.class));
1
2
3
4
5
6

# 2. filter方式

在上一篇介绍WebClient请求头的使用姿势中,除了默认请求头设置之外,还有一个filter的方式,而WebClient正好提供了一个专门用于Basic Auth的Filter

// filter方式
webClient = WebClient.builder().filter(ExchangeFilterFunctions.basicAuthentication("user", "pwd"))
        .baseUrl("http://127.0.0.1:8080").build();
response = webClient.get().uri("/auth?name=一灰灰&age=18").exchange().flatMap(s -> s.toEntity(String.class));

response.subscribe(s -> System.out.println("auth return: " + s));
1
2
3
4
5
6

# 3. 测试与小结

以上代码可以在后文的工程源码中获取,测试输出如下

header auth return: <200 OK OK,auth success: {"name":["一灰灰"],"age":["18"]},[Content-Type:"text/plain;charset=UTF-8", Content-Length:"49"]>
filter auth return: <200 OK OK,auth success: {"name":["一灰灰"],"age":["18"]},[Content-Type:"text/plain;charset=UTF-8", Content-Length:"49"]>
1
2

本文主要介绍了两种WebClient的Basic Auth使用姿势,其原理都是基于设置请求头的方式来实现的

  • 基于WebClient.builder().defaultHeader来手动设置默认请求头
  • 基于WebClient.builder().filter与ExchangeFilterFunctions.basicAuthentication,通过filter来处理请求头

# II. 其他

# 0. 项目

系列博文

  • 【WEB系列】WebClient之请求头设置 (opens new window)
  • 【WEB系列】WebClient之文件上传 (opens new window)
  • 【WEB系列】WebClient之基础使用姿势 (opens new window)
  • 【WEB系列】WebClient之文件上传 (opens new window)

源码

  • 工程:https://github.com/liuyueyi/spring-boot-demo (opens new window)
  • 源码:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/222-web-client (opens new window)

# 1. 一灰灰Blog

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

  • 一灰灰Blog个人博客 https://blog.hhui.top (opens new window)
  • 一灰灰Blog-Spring专题博客 http://spring.hhui.top (opens new window)

一灰灰blog

编辑 (opens new window)
#WebClient
上次更新: 2021/10/15, 19:56:22
【WEB系列】WebClient之请求头设置
【WEB系列】WebClient之超时设置

← 【WEB系列】WebClient之请求头设置 【WEB系列】WebClient之超时设置→

最近更新
01
【基础系列】基于maven多环境配置
04-25
02
【WEB系列】内嵌Tomcat配置Accesslog日志文件生成位置源码探索
04-24
03
【搜索系列】ES查询常用实例演示
04-18
更多文章>
Theme by Vdoing | Copyright © 2017-2022 一灰灰Blog
MIT License | 鄂ICP备18017282号 |
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×