拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 使用Spring Boot和Swagger UI设置JWT

使用Spring Boot和Swagger UI设置JWT

白鹭 - 2021-11-24 607 0 0

1.简介

在这个简短的教程中,我们将了解如何在调用我们的API时将Swagger UI配置为包括JSON Web令牌(JWT)。

2. Maven依赖

在此示例中,我们将使用springfox-boot-starter ,其中包括开始使用Swagger和Swagger UI所需的所有必需依赖项。让我们将其添加到我们的pom.xml文件中:

<dependency>

 <groupId>org.springframework.boot</groupId>

 <artifactId>spring-boot-starter-web</artifactId>

 </dependency>

 <dependency>

 <groupId>io.springfox</groupId>

 <artifactId>springfox-boot-starter</artifactId>

 <version>3.0.0</version>

 </dependency>

3. Swagger配置

首先,我们需要定义ApiKey以将JWT作为授权标头包括在内:

private ApiKey apiKey() {

 return new ApiKey("JWT", "Authorization", "header");

 }

接下来,让我们使用全局AuthorizationScope配置JWT SecurityContext

private SecurityContext securityContext() {

 return SecurityContext.builder().securityReferences(defaultAuth()).build();

 }



 private List<SecurityReference> defaultAuth() {

 AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");

 AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];

 authorizationScopes[0] = authorizationScope;

 return Arrays.asList(new SecurityReference("JWT", authorizationScopes));

 }

然后,我们将API Docket bean配置为包括API信息,安全性上下文和安全性方案:

@Bean

 public Docket api() {

 return new Docket(DocumentationType.SWAGGER_2)

 .apiInfo(apiInfo())

 .securityContexts(Arrays.asList(securityContext()))

 .securitySchemes(Arrays.asList(apiKey()))

 .select()

 .apis(RequestHandlerSelectors.any())

 .paths(PathSelectors.any())

 .build();

 }
private ApiInfo apiInfo() {

 return new ApiInfo(

 "My REST API",

 "Some custom description of API.",

 "1.0",

 "Terms of service",

 new Contact("Sallo Szrajbman", "www.baeldung.com", "[email protected]"),

 "License of API",

 "API license URL",

 Collections.emptyList());

 }

4. REST控制器

在我们的ClientsRestController ,让我们编写一个简单的getClients端点以返回客户端列表:

@RestController(value = "/clients")

 @Api( tags = "Clients")

 public class ClientsRestController {



 @ApiOperation(value = "This method is used to get the clients.")

 @GetMapping

 public List<String> getClients() {

 return Arrays.asList("First Client", "Second Client");

 }

 }

5. Swagger UI

现在,当我们启动应用程序时,我们可以通过http://localhost:8080/swagger-ui/ URL访问Swagger UI。

这是带Authorize按钮的Swagger UI的外观:

使用Spring

当我们单击“ Authorize按钮时,Swagger UI将要求提供JWT。

我们只需要输入令牌并单击Authorize ,然后,对我们API的所有请求将自动在HTTP标头中包含令牌:

使用Spring

6. JWT的API请求

将请求发送到我们的API时,我们可以看到其中包含带有令牌值的“ Authorization”标头:

使用Spring

7.结论

在本文中,我们了解了Swagger UI如何提供自定义配置来设置JWT,这在处理我们的应用程序授权时可能会有所帮助。在Swagger UI中授权后,所有请求将自动包含我们的JWT。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *