若是項目中使用了Oauth2.0,那麼在每次請求接口的時候都須要在header上帶上Authorization
參數才能夠正常訪問,以下所示:java
項目用了Swagger在線接口文檔組件,那麼如何結合Oauth2.0,讓調用接口的時候自動帶上認證參數呢?web
如下就是Oauth2.0整合Swagger的步驟:json
@Configuration @EnableSwagger2 public class SwaggerConfig { private static final String VERSION = "1.0.0"; /** * 建立API */ @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //指定接口包所在路徑 .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() //整合oauth2 .securitySchemes(Collections.singletonList(apiKey())) .securityContexts(Collections.singletonList(securityContext())); } /** * 添加摘要信息 */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .contact(new Contact("JAVA日知錄","http://javadaily.cn","jianzh5@163.com")) .title("account-server接口文檔") .description("account-server接口文檔") .termsOfServiceUrl("http://javadaily.cn") .version(VERSION) .build(); } private ApiKey apiKey() { return new ApiKey("Bearer", "Authorization", "header"); } /** * swagger2 認證的安全上下文 */ private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.any()) .build(); } private List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("web", "access_token"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Collections.singletonList(new SecurityReference("Bearer",authorizationScopes)); } }
http://localhost:8090/auth-service/oauth/token
segmentfault
{ "access_token": "36034ff7-7eea-4935-a3b7-5787d7a65827", "token_type": "bearer", "refresh_token": "4baea735-3c0d-4dfd-b826-91c6772a0962", "expires_in": 36931, "scope": "web" }
Bearer 36034ff7-7eea-4935-a3b7-5787d7a65827
並點擊認證按鈕。
通過以上幾步能夠看到接口請求會默認帶上認證參數,小夥伴們又能夠愉快的玩耍了!api
歡迎掃碼關注微信公衆號或 我的博客