swgger2配置类使用token
时间: 2024-02-24 16:56:53 浏览: 109
要在 Swagger2 中使用 token 进行认证,需要进行以下配置:
1. 在 SwaggerConfig 类中添加 securitySchemes 和 securityContexts:
```java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.securitySchemes(Arrays.asList(apiKey()))
.securityContexts(Arrays.asList(securityContext()));
}
private ApiKey apiKey() {
return new ApiKey("Token Access", "token", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(Arrays.asList(new SecurityReference("Token Access", new AuthorizationScope[0])))
.build();
}
}
```
2. 在需要进行认证的接口上添加 @ApiImplicitParam 注解,指定 header 中传递 token 的名称:
```java
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/user")
@ApiImplicitParam(name = "Authorization", value = "Access Token", required = true, dataType = "string", paramType = "header")
public ResponseEntity<User> getUser(@RequestParam Long id) {
// ...
}
}
```
3. 启动应用程序后,在 Swagger UI 中输入 token 值并点击 Authorize 按钮进行认证。
注意:为了保护敏感数据,建议将 token 存储在环境变量或配置文件中,并在应用程序中进行读取。
阅读全文
相关推荐


















