關於BasicAuth是什麼,以及如何實現鑑權的知識點可以在之前的博文 【WEB系列】RestTemplate之Basic Auth授權 中已經介紹過了,因此本篇將直接進入正文,介紹一下如何在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>

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

當鑑權成功之後,正常返回;當鑑權失敗之後,返回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));

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

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"]>

本文主要介紹了兩種WebClient的Basic Auth使用姿勢,其原理都是基於設置請求頭的方式來實現的

  • 基於 WebClient.builder().defaultHeader 來手動設置默認請求頭
  • 基於 WebClient.builder().filterExchangeFilterFunctions.basicAuthentication ,通過filter來處理請求頭

II. 其他

0. 項目

系列博文

源碼

1. 一灰灰Blog

盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激

下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛

打賞 如果覺得我的文章對您有幫助,請隨意打賞。

相關文章