SpringBoot集成Swagger2登錄功能和安全認證

本篇文章要實現的功能:

  • 1.集成swagger
  • 2.集成swagger登錄功能,訪問 /swagger-ui.html需要先登錄
  • 3.集成安全認證,訪問接口時攜帶header

在這里插入圖片描述


請求接口時攜帶了上一步輸入的header參數和值
在這里插入圖片描述

1.集成swagger

jdk11,SpringBoot 2.7.13
pom.xml依賴swagger2.10.5

<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.10.5</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.10.5</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-spring-webmvc</artifactId><version>2.10.5</version>
</dependency>

application.yml

swagger:enable: true   #是否開啟swaggerbasic:enable: true  #是否開啟登錄認證username: adminpassword: admin
2.集成swagger登錄功能,訪問 /swagger-ui.html需要先登錄

新建 Swagger2Config

import com.zypcy.mono.interceptor.SwaggerInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.MappedInterceptor;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;import java.util.ArrayList;
import java.util.List;@Configuration
@EnableWebMvc
@EnableSwagger2WebMvc
@ConditionalOnProperty(name = {"swagger.enable"},havingValue = "true",matchIfMissing = false
)
public class Swagger2Config implements WebMvcConfigurer {@Value("${spring.profiles.active}")private String active;@Value("${swagger.basic.username:admin}")private String username;@Value("${swagger.basic.password:admin}")private String password;private String basePackage = "com.zypcy.mono.controller";/*** 開放swagger-ui.html資源* @param registry*/@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");WebMvcConfigurer.super.addResourceHandlers(registry);}/* 在此處配置攔截器,要不然攔不到swagger的靜態資源 */@Bean@ConditionalOnProperty(name = "swagger.basic.enable", havingValue = "true")public MappedInterceptor getMappedInterceptor() {return new MappedInterceptor(new String[]{"/swagger-ui.html", "/v2/api-docs", "/webjars/**"}, new SwaggerInterceptor(username, password));}@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).enable(!"prod".equals(active)).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage(basePackage)).paths(PathSelectors.any()).build().securitySchemes(securitySchemes()).securityContexts(securityContexts());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("Mono API 接口文檔").description("Mono REST API 接口文檔").termsOfServiceUrl("").contact(new Contact("zhuyu", "https://zhuyu.blog.csdn.net", "645906265@qq.com")).license("Mono License Version 2.0").licenseUrl("http://www.xxx.xxx/licenses/LICENSE-2.0").version("1.0").build();}//3.集成安全認證,訪問接口時攜帶headerprivate List<SecurityScheme> securitySchemes() {List<SecurityScheme> res = new ArrayList<>();res.add(new ApiKey("AppId", "AppId", "header"));res.add(new ApiKey("Authorization", "Authorization", "header"));return res;}private List<SecurityContext> securityContexts() {List<SecurityContext> res = new ArrayList<>();res.add(SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/.*")).build());return res;}private List<SecurityReference> defaultAuth() {List<SecurityReference> res = new ArrayList<>();AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];authorizationScopes[0] = authorizationScope;res.add(new SecurityReference("AppId", authorizationScopes));res.add(new SecurityReference("Authorization", authorizationScopes));return res;}/*** 添加header,調用代碼:this.header("x-request-info", "string", false, "appId=101;token=a256f4c4f38a76115355d2d039e2882e;")* @param name* @param type* @param required* @param defaultValue* @return*/private Parameter header(String name, String type, boolean required, String defaultValue) {ParameterBuilder param = new ParameterBuilder();return param.name(name).modelRef(new ModelRef(type)).parameterType("header").defaultValue(defaultValue).required(required).build();}}

創建攔截器 SwaggerInterceptor

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Base64;/*** @Description:* @Author: zhuyu* @Date: 2023/11/22 20:44*/
public class SwaggerInterceptor implements HandlerInterceptor {private String username;private String password;public SwaggerInterceptor(String username, String password) {this.username = username;this.password = password;}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String authorization = request.getHeader("Authorization");boolean isAuthSuccess = httpBasicAuth(authorization);if (!isAuthSuccess) {response.setCharacterEncoding("utf-8");response.setStatus(401);response.setHeader("WWW-authenticate", "Basic realm=\"Realm\"");try (PrintWriter writer = response.getWriter()) {writer.print("Forbidden, unauthorized user");}}return isAuthSuccess;}public boolean httpBasicAuth(String authorization) throws IOException {if (authorization != null && authorization.split(" ").length == 2) {String userAndPass = new String(Base64.getDecoder().decode((authorization.split(" ")[1])));String username = userAndPass.split(":").length == 2 ? userAndPass.split(":")[0] : null;String password = userAndPass.split(":").length == 2 ? userAndPass.split(":")[1] : null;if (this.username.equals(username) && this.password.equals(password)) {return true;}}return false;}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {String uri = request.getRequestURI();AntPathMatcher pathMatcher = new AntPathMatcher();if (!pathMatcher.match("/swagger-ui.html", uri) && !pathMatcher.match("/webjars/**", uri)) {response.setStatus(404);return;}ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource[] resources = resolver.getResources("classpath:/META-INF/resources" + uri);if (resources != null && resources.length > 0) {FileCopyUtils.copy(resources[0].getInputStream(), response.getOutputStream());} else {response.setStatus(404);}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/160315.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/160315.shtml
英文地址,請注明出處:http://en.pswp.cn/news/160315.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

內網配置git代理

http、https訪問 [http]proxy socks5://192.168.102.xxx:xxxx [https]proxy socks5://192.168.102.xxx:xxx設置ssh訪問 需要修改~/.ssh/config文件&#xff08;&#xff09;, 沒有的話新建一個. 同樣僅為github.com設置代理需要注意~/.ssh/config文件權限為600&#xff0c;…

C語言 子函數調malloc申請內存返回給主函數使用——可行,但要注意

一般情況&#xff0c;子函數中動態申請內存&#xff0c;將地址返回給主函數&#xff0c;理論上應該也是可以的&#xff0c;需要子函數返回動態內存地址&#xff0c;主函數實參是相應的地址變量即可。只不過&#xff0c;主函數實參傳入子函數之前&#xff0c;可能會將指針置空&a…

MatrixOne實戰系列回顧 | 導入導出項目場景實踐

本次分享主要介紹MatrixOne導入導出以及項目場景實踐。將從四個方向為大家演示MatrixOne的功能&#xff0c;分別是數據的導入、導出、對接數據集成工具&#xff0c;以及Java連接實戰。 數據導入會使用三種方式將數據導入至 MatrixOne中。分別是insert語句、load data語句還有s…

學習Opencv(蝴蝶書/C++)——3. OpenCV的數據類型

文章目錄 1. 總覽2. 基礎類型2.0 基礎類型總覽2.1 cv::Vec<>類2.2 cv::Matx<>類2.3 cv::Point類(cv::Point3_< >和cv::Point_< >)2.4 cv::Scalar(cv::Scalar_)類2.5 cv::Size(cv::Size_)類、cv::Rect(cv::Rect_)類和cv::RotatedRect 類2.6 基礎類型…

常見面試題-Redis 主從復制原理以及痛點

Redis 主從復制如何同步數據呢&#xff1f; 參考文章&#xff1a;https://blog.csdn.net/Seky_fei/article/details/106877329 https://zhuanlan.zhihu.com/p/55532249 https://cloud.tencent.com/developer/article/2063597 https://xie.infoq.cn/article/4cffee02a2a12c2…

LongAccumulator

原子操作之LongAccumulator 和LongAdder的區別在于&#xff0c;LongAdder是在Cell里面只能做加減操作&#xff0c;不能乘除&#xff0c;而LongAccumulator就可以定義乘除操作。原理和LongAdder都是一樣的&#xff0c;一個Base和一個Cells數組。 原文跳轉地址

pyqt5的組合式部件制作(四)

對組合式部件的制作又改進了一版&#xff0c;組合式部件的子部件不再需要單獨“提升為”&#xff0c;如果在模板文件的提升部件窗口內選擇了“全局包含”&#xff0c;那么只需要在模板文件和應用文件中直接復制粘貼即可&#xff0c;部件的應用更為簡便。如下圖&#xff1a;按住…

2023秋招上岸必備軟件測試面試題

1、請結合你熟悉的項目&#xff0c;介紹一下你是怎么做測試的&#xff1f; -首先要自己熟悉項目&#xff0c;熟悉項目的需求、項目組織架構、項目研發接口等 -功能 接口 自動化 性能 是怎么處理的&#xff1f; -第一步&#xff1a; 進行需求分析&#xff0c;需求評審&#…

【Delphi】開發IOS 程序,TLabel 中英文字對齊(水平),一行代碼解決顯示對齊問題!

目錄 一、問題現象&#xff1a; 二、解決方案&#xff08;一行代碼解決ios對齊問題&#xff09;&#xff1a; 三、解決后效果&#xff1a; 四、后記&#xff1a; 一、問題現象&#xff1a; 在用 Delphi 開發ios程序時&#xff0c;使用TLabel控件顯示&#xff0c;會出現中英…

WiFi 6的數據在發送端分片和在接收端重組的理解

802.11ax是WiFi 6標準&#xff0c;其引入了一些新的特性和技術來提升無線網絡的性能&#xff0c;其中包括幀聚合和幀分片。以下是它們的詳細處理流程&#xff1a; 1. 幀聚合 幀聚合是一種提高傳輸效率的技術&#xff0c;它允許多個數據幀被聚合到一起&#xff0c;然后作為一個…

layui(2.8.18)生成驗證碼

<!DOCTYPE html> <html> <head><meta charset"utf-8"><title>登入</title><meta name"renderer" content"webkit"><meta http-equiv"X-UA-Compatible" content"IEedge,chrome1&quo…

Go 工具鏈詳解(七):模塊緩存清理工具

go mod 緩存 在 Golang 中&#xff0c;模塊是對一組版本化的包的集合的描述。Go 1.11 版本引入了模塊支持&#xff0c;通過 go mod 命令提供了對模塊的管理。Go 模塊的一個重要特性是依賴管理&#xff0c;可以清晰地定義項目所依賴的模塊及對應的版本&#xff0c;并確保代碼使…

電磁優化的并行空間映射方法

空間映射(SM)是一種公認的加速電磁優化的方法。現有的SM方法大多基于順序計算機制。本文提出了一種用于電磁優化的并行SM方法。在該方法中&#xff0c;每次迭代開發的代理模型被訓練以同時匹配多個點的精細模型。多點訓練和SM使代理模型在比標準SM更大的鄰域內有效。本文提出的…

[補題記錄] Complete the Permutation(貪心、set)

URL&#xff1a;https://codeforces.com/group/OcmZ7weh45/contest/487583/problem/J 目錄 Problem/題意 Thought/思路 Code/代碼 Problem/題意 給出一個長度為 N 的序列&#xff0c;其中的元素都是奇數。 現在要求在兩個奇數之間插入一個偶數&#xff0c;使得這三個數遞增…

信息壓縮模型在自然語言處理中的應用和探討

信息壓縮模型在自然語言處理中的應用和探討 摘要:正文:結論:附錄:摘要: 隨著人工智能和深度學習的發展,自然語言處理(NLP)在信息處理中的角色變得越來越重要。然而,海量的自然語言數據為信息處理帶來了挑戰——更多的信息通常意味著更高的處理成本,并可能導致效率降低。為…

一個工具讓你明白“萬丈高樓平地起”,拒絕重復造輪子!

大家在公司工作當中是不是很多時間裝環境很麻煩&#xff0c;一個項目要上線了&#xff0c;開始網上搜了一邊又一遍的環境搭建教程&#xff1f;等到下一個項目要上線了&#xff0c;又上網上搜了一邊又一遍的環境搭建教程。關鍵天花亂墜的互聯網&#xff0c;找不到很靠譜的呀。有…

數組的移動

設計程序&#xff0c;給定包含N個整數的數組array&#xff0c;實現操作&#xff1a;前面各個整數順序向后移動m個位置&#xff0c;最后的m個整數移動到最前面。方法&#xff1a;void move(int array[], int n,int m ) 輸入要求 第一行輸入兩個整數N(1<N<1e6)和m(0<m&…

webpack 配置

1、基礎配置 // node js核心模塊 const path require(path) // 插件是需要引入使用的 const ESLintPlugin require(eslint-webpack-plugin) // 自動生成index.html const HtmlWebpackPlugin require(html-webpack-plugin); // 將css文件單獨打包&#xff0c;在index.html中…

如何做好項目管理?年薪百萬項目大佬一直在用這11張圖

大家好&#xff0c;我是老原。 日常工作中&#xff0c;我們會遇到各種大大小小的工作項目&#xff0c;如何能讓項目保質保量的完成&#xff0c;是我們項目經理的目標。 項目管理的流程可以說是由一系列的子過程組成的&#xff0c;它是一個循序漸進的過程&#xff0c;所以不能…