swagger oauth2 php,Springboot Oauth2 集成Swagger2权限验证实战

Swagger是什么?能干什么?在这就不展开讲解了。本文主要讲解如何集成OAuth2的Password模式权限验证,验证接口是否具有权限。

引入依赖

io.springfox

springfox-swagger2

2.9.2

io.springfox

springfox-swagger-ui

2.9.2

2.SwaggerConfig配置

package com.entfrm.core.swagger.config;

import com.entfrm.core.base.config.GlobalConfig;

import io.swagger.annotations.ApiOperation;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.OAuthBuilder;

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.Arrays;

import java.util.Collections;

/**

* @author entfrm

* @date 2020/4/14

* @description swagger 配置

*/

@Configuration

@EnableSwagger2

public class SwaggerConfig {

@Bean

public Docket createRestApi() {

return new Docket(DocumentationType.SWAGGER_2)

.pathMapping("/dev")

.apiInfo(apiInfo())

.select()

.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

.paths(PathSelectors.any())

.build()

.securitySchemes(Collections.singletonList(securitySchemes()))

.securityContexts(Collections.singletonList(securityContexts()));

}

/**

* 认证方式使用密码模式

*/

private SecurityScheme securitySchemes() {

GrantType grantType = new ResourceOwnerPasswordCredentialsGrant("/dev/oauth/token");

return new OAuthBuilder()

.name("Authorization")

.grantTypes(Collections.singletonList(grantType))

.scopes(Arrays.asList(scopes()))

.build();

}

/**

* 设置 swagger2 认证的安全上下文

*/

private SecurityContext securityContexts() {

return SecurityContext.builder()

.securityReferences(Collections.singletonList(new SecurityReference("Authorization", scopes())))

.forPaths(PathSelectors.any())

.build();

}

/**

* 允许认证的scope

*/

private AuthorizationScope[] scopes() {

AuthorizationScope authorizationScope = new AuthorizationScope("test", "接口测试");

AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];

authorizationScopes[0] = authorizationScope;

return authorizationScopes;

}

/**

* 添加摘要信息

*/

private ApiInfo apiInfo() {

// 用ApiInfoBuilder进行定制

return new ApiInfoBuilder()

// 设置标题

.title(GlobalConfig.getName())

// 描述

.description(GlobalConfig.getName() + "接口文档")

// 作者信息

.contact(new Contact("entfrm", "http://47.100.3.58/", "1029861695@qq.com"))

// 版本

.version("版本号:" + GlobalConfig.getVersion())

.build();

}

}

3.在Controller中注解@ Api,@ApiOperation

/**

* @author entfrm

* @date 2020-04-01 10:04:11

* @description 文章Controller

*/

@Api("文章管理")

@RestController

@AllArgsConstructor

@RequestMapping("/cms/article")

public class ArticleController {

private final CategoryService categoryService;

private final ArticleService articleService;

@ApiOperation("文章列表")

@PreAuthorize("@ps.hasPerm('article_view')")

@GetMapping("/list")

@ResponseBody

public R list(Page page, Article article) {

IPage articlePage = articleService.page(page, getQueryWrapper(article));

return R.ok(articlePage.getRecords(), articlePage.getTotal());

}

}

4.重启看下效果

03e3e424e75718231b5ebf9779f064c6.gif

5.码云地址

Spring Boot是一个快速开发框架,Swagger是一个API文档生成工具,OAuth2是一个授权框架,可以用于保护API。 下面是Spring Boot集成SwaggerOAuth2的代码实现和原理解释: 1. 添加Swagger依赖 在pom.xml中添加Swagger依赖: ```xml <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配置 在Spring Boot的配置类中添加Swagger配置: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 3. 添加OAuth2依赖 在pom.xml中添加OAuth2依赖: ```xml <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.4.RELEASE</version> </dependency> ``` 4. 添加OAuth2配置 在Spring Boot的配置类中添加OAuth2配置: ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(); } } ``` 5. 添加Token鉴权 添加Token鉴权的方式是在控制器方法上添加@PreAuthorize注解,指定需要的角色或权限: ```java @RestController @RequestMapping("/api") public class ApiController { @GetMapping("/hello") @PreAuthorize("hasRole('ADMIN')") public String hello() { return "Hello World!"; } } ``` 6. 请求Token 使用OAuth2的客户端工具请求Token: ```java public class OAuth2Client { public static void main(String[] args) { Base64.Encoder encoder = Base64.getEncoder(); String clientCredentials = "client_id:client_secret"; String encodedClientCredentials = encoder.encodeToString(clientCredentials.getBytes()); String url = "http://localhost:8080/oauth/token"; HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.add("Authorization", "Basic " + encodedClientCredentials); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("grant_type", "client_credentials"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); System.out.println(response.getBody()); } } ``` 以上就是Spring Boot集成SwaggerOAuth2的代码实现和原理解释。其中Swagger用于生成API文档,OAuth2用于保护API,Token鉴权用于限制访问API的角色或权限
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值