Swagger整合Jwt授权配置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swagger整合Jwt授权配置相关的知识,希望对你有一定的参考价值。
参考技术A Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,它有着如下的优点:1)及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)
2)规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)
3)一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)
4)可测性 (直接在接口文档上进行测试,以方便理解业务)
1)添加pom.xml依赖
<pre class="md-fences md-end-block md-fences-with-lineno" lang="xml" contenteditable="false" cid="n252" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency></pre>
2)创建swagger配置文件
<pre class="md-fences md-end-block md-fences-with-lineno" lang="java" contenteditable="false" cid="n255" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
@Configuration
@EnableSwagger2
public class Swagger2Config
</pre>
3)启动程序
访问路径: http://localhost:8081/swagger-ui.html ,出现生成的文档页面。
此为原生界面,很难看,所以我们需要引入swagger-bootstrap-ui,也就是Knife4j的前身
4)使用Knife4j
a)添加pom.xml依赖
<pre class="md-fences md-end-block md-fences-with-lineno" lang="xml" contenteditable="false" cid="n268" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency></pre>
b)开启Swagger2配置
<pre class="md-fences md-end-block md-fences-with-lineno" lang="java" contenteditable="false" cid="n271" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class Swagger2Config
@Bean
public Docket createRestApi()
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.apiInfo(apiInfo())
.select()
//swagger要扫描的包路径
.apis(RequestHandlerSelectors.basePackage("com.dsblog.server.controller"))
.paths(PathSelectors.any())
.build()
b)重启服务
访问地址: http://localhost:8081/doc.html ,这个ui界面看起来就更美观,更符合国人的使用习惯
1、添加pom.xml依赖
<pre class="md-fences md-end-block md-fences-with-lineno" lang="xml" contenteditable="false" cid="n282" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=" http://maven.apache.org/POM/4.0.0 " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">
<modelVersion>4.0.0</modelVersion>
</project></pre>
2、创建Swagger2Config配置文件
<pre class="md-fences md-end-block md-fences-with-lineno" lang="java" contenteditable="false" cid="n285" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
package com.dsblog.server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class Swagger2Config
@Bean
public Docket createRestApi()
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.apiInfo(apiInfo())
.select()
//swagger要扫描的包路径
.apis(RequestHandlerSelectors.basePackage("com.dsblog.server.controller"))
.paths(PathSelectors.any())
.build()
.securityContexts(securityContexts())
.securitySchemes(securitySchemes());
</pre>
3、创建SecurityConfig配置文件
<pre class="md-fences md-end-block md-fences-with-lineno" lang="java" contenteditable="false" cid="n288" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
package com.dsblog.server.config.security;
import com.dsblog.server.model.User;
import com.dsblog.server.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
</pre>
4、创建测试Controller,其中/login登录和/logout退出方法不需要Authorize验证,和上面的重写方法<mark style="box-sizing: border-box; background: rgb(255, 255, 0); color: rgb(0, 0, 0);">configure(WebSecurity web)</mark>匹配,user/info方法需要Authorize验证才能进行访问
<pre class="md-fences md-end-block md-fences-with-lineno" lang="java" contenteditable="false" cid="n291" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: monospace, monospace; font-size: 0.9em; white-space: pre; display: block; break-inside: avoid; text-align: left; background-image: ; background-position: var(--code-block-bg-color); background-size: ; background-repeat: var(--code-block-bg-color); background-attachment: ; background-origin: ; background-clip: ; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">
package com.dsblog.server.controller;
import com.dsblog.server.model.ResultBean;
import com.dsblog.server.model.User;
import com.dsblog.server.model.UserLoginParam;
import com.dsblog.server.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
@Api(tags = "LoginController")
@RestController
public class LoginController
</pre>
5、重启程序,输入 http://localhost:8081/doc.html
6、测试
5)携带token发送到后台获取用户信息,验证通过
Swagger + spring boot + jwt + 如何禁用特定 API 的授权按钮
【中文标题】Swagger + spring boot + jwt + 如何禁用特定 API 的授权按钮【英文标题】:Swagger + spring boot + jwt + How to disable Authorize button for specific API 【发布时间】:2021-05-16 07:50:20 【问题描述】:我已经在我的 Spring Boot 应用程序中配置了 JWT Bearer 令牌认证。我有“Authenticate”和“Hello”控制器,其中“Hello”控制器将承载令牌作为授权标头。 “Authenticate” api 生成不记名令牌。邮递员一切正常。但是从大摇大摆的角度来看,我无法为“Authenticate” api 禁用“Authorize”按钮。 swagger screen clip
我的代码如下所示: SwaggerConfig 文件:
@Bean
public Docket swaggerSpringfoxDocket()
Contact contact = new Contact(
"shivaraj",
"https://shivaraj.co",
"bmxxxxx@xxxx.com");
List<VendorExtension> vext = new ArrayList<>();
ApiInfo apiInfo = new ApiInfo(
"Backend API",
"description",
"1.0.0",
"https://shivaraj.co",
contact,
"MIT",
"https://shivaraj.co",
vext);
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.pathMapping("/")
.apiInfo(ApiInfo.DEFAULT)
.forCodeGeneration(true)
.genericModelSubstitutes(ResponseEntity.class)
.ignoredParameterTypes(SpringDataWebProperties.Pageable.class)
.ignoredParameterTypes(java.sql.Date.class)
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
.directModelSubstitute(java.time.LocalDateTime.class, Date.class)
.securityContexts(Lists.newArrayList(securityContext()))
.securitySchemes(Lists.newArrayList(apiKey()))
.useDefaultResponseMessages(false);
docket = docket.select()
.paths(regex(DEFAULT_INCLUDE_PATTERN))
.build();
return docket;
private ApiKey apiKey()
return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
private SecurityContext securityContext()
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex(DEFAULT_INCLUDE_PATTERN))
.build();
List<SecurityReference> defaultAuth()
AuthorizationScope authorizationScope
= new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(
new SecurityReference("JWT", authorizationScopes));
作为替代方法,有没有一种方法可以为每个单独的控制器在 swagger 中启用授权按钮?
【问题讨论】:
我自己解决了。仅针对其他人:将“security = @SecurityRequirement(name = "bearerAuth")”添加到@Operation 标签允许启用/禁用令牌身份验证。 【参考方案1】:将security = @SecurityRequirement(name = "bearerAuth")
添加到@Operation
标签允许启用/禁用令牌身份验证。
【讨论】:
以上是关于Swagger整合Jwt授权配置的主要内容,如果未能解决你的问题,请参考以下文章
Swagger + spring boot + jwt + 如何禁用特定 API 的授权按钮
如何使用 openapi-ui 和承载令牌(jwt)在 swagger-ui 中激活授权按钮?