1. 程式人生 > >Spring Boot 整合 Swagger2 與配置 OAuth2.0 授權

Spring Boot 整合 Swagger2 與配置 OAuth2.0 授權

Spring Boot 整合 Swagger2 很簡單,由於介面採用了OAuth2.0 & JWT 協議做了安全驗證,使用過程中也遇到了很多小的問題,多次嘗試下述配置可以正常使用。

Maven

        <!-- swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <
version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> <
dependency> <groupId>io.springfox</groupId> <artifactId>springfox-bean-validators</artifactId> <version>2.8.0</version> </dependency>
Swagger2Configuration
@Configuration
@EnableSwagger2
public class Swagger2Configuration {

   
// @Value("${config.oauth2.accessTokenUri}") private String accessTokenUri ="http://localhost:8080/oauth/token"; private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API 介面服務") .description("API 介面服務") .termsOfServiceUrl("http://www.cnblogs.com/irving") .version("v1") .license("Apache License Version 2.0") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .contact(new Contact("irving","http://www.cnblogs.com/irving","[email protected]")) .build(); } @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.holiday.sunweb.controller")) //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .securityContexts(Collections.singletonList(securityContext())) .securitySchemes(Arrays.asList(securitySchema(), apiKey(), apiCookieKey())); // .globalOperationParameters( // newArrayList(new ParameterBuilder() // .name("access_token") // .description("AccessToken") // .modelRef(new ModelRef("string")) // .parameterType("query") // .required(true) // .build())); } @Bean public SecurityScheme apiKey() { return new ApiKey(HttpHeaders.AUTHORIZATION, "apiKey", "header"); } @Bean public SecurityScheme apiCookieKey() { return new ApiKey(HttpHeaders.COOKIE, "apiKey", "cookie"); } private OAuth securitySchema() { List<AuthorizationScope> authorizationScopeList = newArrayList(); authorizationScopeList.add(new AuthorizationScope("read", "read all")); authorizationScopeList.add(new AuthorizationScope("write", "access all")); List<GrantType> grantTypes = newArrayList(); GrantType passwordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(accessTokenUri); grantTypes.add(passwordCredentialsGrant); return new OAuth("oauth2", authorizationScopeList, grantTypes); } private SecurityContext securityContext() { return SecurityContext.builder().securityReferences(defaultAuth()) .build(); } private List<SecurityReference> defaultAuth() { final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3]; authorizationScopes[0] = new AuthorizationScope("read", "read all"); authorizationScopes[1] = new AuthorizationScope("trust", "trust all"); authorizationScopes[2] = new AuthorizationScope("write", "write all"); return Collections.singletonList(new SecurityReference("oauth2", authorizationScopes)); } // @Bean // public SecurityConfiguration security() { // return new SecurityConfiguration // ("client", "secret", "", "", "Bearer access token", ApiKeyVehicle.HEADER, HttpHeaders.AUTHORIZATION,""); // } @Bean SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId("client_test") .clientSecret("secret_test") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .deepLinking(true) .displayOperationId(false) .defaultModelsExpandDepth(1) .defaultModelExpandDepth(1) .defaultModelRendering(ModelRendering.EXAMPLE) .displayRequestDuration(false) .docExpansion(DocExpansion.NONE) .filter(false) .maxDisplayedTags(null) .operationsSorter(OperationsSorter.ALPHA) .showExtensions(false) .tagsSorter(TagsSorter.ALPHA) .validatorUrl(null) .build(); } }
UserController
@Api(value = "使用者介面服務", description = "使用者介面服務")
@RestController
@RequestMapping("/api/v1/users")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserRepository userRepository;

    @ApiOperation(value = "查詢通過 OAuth2.0 授權後獲取的使用者資訊", notes = "通過 OAuth2.0 授權後獲取的使用者資訊")
    @GetMapping("/principal")
    public Principal principal(Principal principal)
    {
        return principal;
    }


    @ApiOperation(value = "根據使用者名稱查詢使用者資訊", notes = "根據使用者名稱查詢使用者資訊")
    @GetMapping("/{username}")
    public BaseMsg GetUserInfoByUserName(@PathVariable String username) {
        return BaseMsgResponse.success(userRepository.findOneByusername(username));
    }

    @ApiOperation(value = "根據ID刪除一個使用者", notes = "根據ID刪除一個使用者")
    @DeleteMapping("/{id}")
    public BaseMsg getInfoByName(@PathVariable Integer id) {
        userRepository.deleteById(id);
        return BaseMsgResponse.success();
    }
}

image

配置 Resource Owner Password Credentials 模式的 Client

image

Test

image

問題:

swagger-2.9.1 /csrf is 404 問題 

配置 ApiKey 後 HTTP 頭 Authorization: Bearer {THE TOKEN} 不生效問題

@Bean
    public SecurityScheme apiKey() {
        return new ApiKey(HttpHeaders.AUTHORIZATION, "apiKey", "header");
    }

後面使用了 OAuth2.0 協議在 2.8.0 版本中無問題。

相關推薦

Spring Boot 整合 Swagger2 配置 OAuth2.0 授權

Spring Boot 整合 Swagger2 很簡單,由於介面採用了OAuth2.0 & JWT 協議做了安全驗證,使用過程中也遇到了很多小的問題,多次嘗試下述配置可以正常使用。 Maven <!-- swagger2 --> <dependen

Spring Boot 整合 swagger2 自動生成 RESTFul API 文檔

pat turn ket config 文件 pen 用戶 配置文件 方式 1)首先編輯pom.xml添加依賴 <dependency>   <groupId>io.springfox</groupId>   <artifactI

Spring Boot學習總結】14.Spring Boot整合Redis-傳統方式對比

前面我們講解了如何使用Spring Boot來控制事務,下面我們來講解一下如何使用Spring Boot來整合Redis 為了對比傳統工程與Spring Boot整合的不同,以及彰顯Spring Boot整合的優勢,我們會逐一剖析傳統整合方式與Spring Boot整合方式。 一、傳統方式整

Spring Boot整合Swagger2

Spring Boot整合Swagger2 Swagger 介紹 新增入Swagger2的依賴 configuration Swagger 各註解說明 測試 swagger 聚合多個專案 跨域問題 全域性配置

第六篇:Spring Boot整合Swagger2構建RESTful API文件

由於Spring Boot有快速開發、便捷部署等特性,所以很大一部分Spring Boot的使用者會用來構建RESTfulAPI。而我們構建RESTfulAPI的目的通常都是由於多終端的原因,這些終端會共用很多底層業務邏輯,因此我們會抽象出這樣一層來同時服務於多個移動端或者Web前端。

高併發架構實戰(六) Spring Boot 整合 Swagger2

Spring Boot 2.0.4 整合 swagger 2.9.2。 專案原始碼地址 一、簡介 Swagger是一款Restful介面的文件線上自動生成的軟體,也能進行功能測試。 二、使用方法 先看下目錄結構 ~/workspace/gitee/high-c

Spring Boot 整合dubbozookeeper實現不同專案之間資料通過服務的傳遞

一、安裝zookeeper 1、下載路徑:http://mirrors.hust.edu.cn/apache/zookeeper/ 可以自己選擇版本進行下載(同時支援windows和linux) 2、目錄結構 3、修改conf下的配置檔案zoo.cfg 4、

spring boot整合mybatis--xml配置

spring boot整合mybatis–xml配置 1.配置application.yml連線資料庫,mapper-locations 指明mapper.xml對映檔案的包,type-aliases-package掃描的包名 spring: dataso

Spring Boot 整合 Druid (配置屬性列表)

Druid是JAVA中最常用的資料庫連線池 pom.xml <!-- alibaba的druid資料庫連線池 --> <dependency> <groupId>com.alibaba</group

第九篇: 用spring boot整合swagger2建立API文件

簡介: Swagger的目標是為REST APIs 定義一個標準的,與語言無關的介面,使人和計算機在看不到原始碼或者看不到文件或者不能通過網路流量檢測的情況下能發現和理解各種服務的功能。當服務通過Swagger定義,消費者就能與遠端的服務互動通過少量的實現邏輯。類似於低階程

Spring Boot整合swagger2,搭建Restful API線上文件

        Swagger,中文“拽”的意思,它是一個強大的線上API文件的框架,目前它的版本是2.x,所以稱為“swagger2”。swagger2提供了線上文件的查閱和測試功能。利用Swagger2很容易構建RESTf

spring boot 整合 swagger2 並定製RestFul API介面

1、新增maven依賴: <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <versi

Spring Boot整合MyBatis分頁外掛

1.MyBatisConfig.java @Configuration @EnableTransactionManagement public class MyBatisConfig impleme

Spring boot整合Swagger2頁面 不顯示的3個常見原因

第一種原因 我遇到兩次 如下圖;解決方法    1:<dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox

spring boot 整合shiro的配置

spring boot提供了一個自帶的認證框架,同時也提供自定義的javaconfig配置擴充套件,spring-sercurity同樣也是優秀的框架,但是習慣了用apache shiro框架,而且原專案就是整合的shiro框架,到網上找了一下配置方式,沒找到完

spring boot 整合 swagger2 遇到的坑!!!

整合步驟: 1.加入相關依賴 2.新增 SwaggerConfig配置類 這是因為訪問不到靜態資源,需要新增。這裡網上教程很多,不提。 我的錯誤:添加了這些配置仍然訪問不到,顯然不是網上教程的問題,最後有一個部落格說這些靜態資源其實是在 swagger-ui這個包

kafka學習筆記(三)spring boot整合kafka0.9.0.1(使用配置類)

spring boot 版本:1.5.6引入關於kafka的相關jar         <dependency>          <groupId>org.springframework.kafka</groupI

Spring Boot 揭秘實戰(四) 配置文件篇 - 有哪些很棒的特性

real randint 開發人員 hat mod 配置管理 bsp footer tar 文章目錄 1. 使用屬性文件2. YAML文件 1.1. 自定義屬性 1.2. 參數引用 1.3. 隨機數屬性 1.4. application-{profile}.proper

spring boot整合mybatis深坑之c3p0的詳細配置

text context ati reat source ast type fig oot 項目地址:https://gitee.com/zhangjunqing/spring-boot/tree/master/springboot-mybatis-notice 本人在c3

Spring Boot整合攜程Apollo配置中心

batch sts ade 文件 context rac bean -m space 攜程官網對apollo的使用講解了很多種方式的使用,但是感覺一些細節還是沒講全,特別是eureka配置中心地址的配置 這裏對springboot整合apollo說一下 >Spri