前前言
spring security Oauth2 和 swagger2 是什么呢宾尚?簡單介紹一下降淮,但是如果不明白的話不適合看這個文章醇锚。
- spring security Oauth2
一個很好用的安全框架,可以很輕松的實現(xiàn)細粒度的接口防護 - swagger2
這是一個動態(tài)生成 api 文檔的東西改艇,有了這個東西媽媽再也不用擔心一邊維護代碼一邊維護文檔了。
前言
spring security Oauth2 的使用在我的其他博客中也講到了坟岔,這里就不在敘述谒兄。這篇文章主要講述的就是我們的應用已經被 spring security Oauth2 保護的情況下,集成 swagger2 生成api文檔社付。
大概實現(xiàn)步驟
- 引入 pom 依賴(假如你的項目是使用 Maven 管理承疲,如果使用的不是 Maven 的話你知道該怎么做)
- refresh 一下 pom (有的小朋友會遺忘)
- 新建一個 swagger2 的配置類
- 把 swagger2 使用的接口放行(被 Oauth2 攔了還玩?zhèn)€毛線)
具體編碼實現(xiàn)
- pom依賴
<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>
這里注意我使用的是2.8.0
版本,為什么是這個版本呢鸥咖?我試了2.9.x
燕鸽,也試了2.7.x
,有一些問題只有2.8.0
解決了啼辣,例如“接口返回示例”部分只有2.8.0
按照Java類書寫的順序顯示啊研,其他版本是按照字符串順序顯示。其他問題我就不一一列舉了鸥拧,大家嘗試一下党远,也沒必要一定使用2.8.0
。更換版本的話只需要改一下 pom 里面的版本即可住涉,其他配置不用變麸锉。jsonview 組件截止鄙人寫博客的時候 swagger2 都沒有支持
- 新建 swagger2 配置類
package com.ybk.ordering.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
//把import寫進來主要是為了確保萬無一失
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//這個東西是項目的根路徑,也就是“/oauth/token”前面的那一串
//這個東西在配置文件里寫的舆声,大家也可以直接寫死在配置文件中
@Value("${auth_server}")
private String AUTH_SERVER;
/**
* 主要是這個方法花沉,其他的方法是抽出去的,所以大家不要害怕為啥有這么多方法
* 在 basePackage 里面寫需要生成文檔的 controller 路徑
*/
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.ybk.ordering.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.securitySchemes(Collections.singletonList(securityScheme()))
.securityContexts(Collections.singletonList(securityContext()));
}
/**
* 這個方法主要是寫一些文檔的描述
*/
private ApiInfo apiInfo() {
return new ApiInfo(
"某某系統(tǒng)API",
"This is a very pretty document!",
"1.0",
"",
new Contact("師父領進門", "", "qixiazhen@qq.com"),
"", "", Collections.emptyList());
}
/**
* 這個類決定了你使用哪種認證方式媳握,我這里使用密碼模式
* 其他方式自己摸索一下碱屁,完全莫問題啊
*/
private SecurityScheme securityScheme() {
GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(AUTH_SERVER + "/oauth/token");
return new OAuthBuilder()
.name("spring_oauth")
.grantTypes(Collections.singletonList(grantType))
.scopes(Arrays.asList(scopes()))
.build();
}
/**
* 這里設置 swagger2 認證的安全上下文
*/
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("spring_oauth", scopes())))
.forPaths(PathSelectors.any())
.build();
}
/**
* 這里是寫允許認證的scope
*/
private AuthorizationScope[] scopes() {
return new AuthorizationScope[]{
new AuthorizationScope("all", "All scope is trusted!")
};
}
}
大體上就些配置,如果有哪些方法調用我沒說明白或者沒法兒理解的話用 IDE 進去看看源碼的注釋基本也就明白了蛾找。
- Oauth2 放行 swagger2
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(
"/webjars/**",
"/resources/**",
"/swagger-ui.html",
"/swagger-resources/**",
"/v2/api-docs")
.permitAll();
}
}
如你所見娩脾,配置寫在資源服務器里面。這里是簡化的代碼打毛,實際使用中你在原有配置的基礎上把我上面寫的這些路徑放行即可柿赊。
- 完成了俩功,試一試
瀏覽器打開項目根路徑/swagger-ui.html
,我這里揪一個生產環(huán)境上的例子給你們瞟一眼
swagger2主頁
現(xiàn)在點擊圖片右上角那個
Authorize
按鈕認證
然后正常的輸入信息認證即可訪問接口了
后記
這篇文章的重點主要是在 spring security Oauth2 下使用 swagger2 碰声,所以關于 swagger2 的一些注解就不詳細講了诡蜓,例如@Api
、@ApiParam
等等胰挑,大家可以邊查邊用蔓罚,很簡單。
穩(wěn)當當瞻颂!