Spring Security接管Swagger认证授权,我也只用了三行代码

本文介绍了如何在Spring Security框架下接管Swagger的认证授权,仅需三行代码即可实现。主要内容包括添加相关依赖,配置Swagger扫描路径,设置Spring Security的内存账号及授权规则,最后通过测试验证了方案的有效性。
摘要由CSDN通过智能技术生成

接上篇《Apache Shiro 接管Swagger认证授权》,有热心网友反应Apache Shiro似乎太简单。针对这个问题,个人不做任何评价(一切技术服务于需求)。今天主要分享内容为:在Spring Security下如何接管Swagger的认证授权工作。

1.添加依赖

假定你对Swagger和Spring Security已经有一定的基础,现在开始检查你的项目中是否添加了Swagger和Spring Security的依赖。以Maven为例,向pom.xml文件添加如下配置信息:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2.配置Swagger

Swagger的配置相对比较简单,最主要的是配置其扫描的包路径,其他信息可以选配。你可以按照下列方式进行配置:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration
Spring Security整合Swagger的过程中,我们需要进行以下几个步骤: 1. 配置Spring Security:在Spring Security配置类中,我们可以使用`WebSecurityConfigurerAdapter`来配置权限过滤和访问控制。可以在`configure(HttpSecurity http)`方法中添加`.antMatchers("/swagger-ui.html").permitAll()`来允许Swagger UI页面的访问。这样,Swagger UI页面将不会被Spring Security拦截。 2. 配置静态资源:Swagger UI页面需要访问一些静态资源,例如Swagger API文档和UI配置文件。我们可以在Spring Security配置类中使用`WebSecurity.configure(WebSecurity web)`方法来配置这些静态资源的访问权限。可以使用`web.ignoring().antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html")`来允许这些静态资源的访问。 3. 添加相关依赖:在项目的pom.xml文件中,我们需要添加Spring SecuritySwagger的相关依赖。可以添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` 这些依赖将帮助我们实现Spring SecuritySwagger的整合。 综上所述,以上是实现Spring Security整合Swagger的方法。通过配置Spring Security和静态资源,以及添加相关依赖,我们可以实现在Spring Boot项目中使用Spring Security保护接口并允许Swagger UI的访问[1]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值