Swagger整合Oauth2

若是項目中使用了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));
    }
}

使用步驟

  • 使用postman調用認證中心接口獲取access_token

http://localhost:8090/auth-service/oauth/tokensegmentfault

{
  "access_token": "36034ff7-7eea-4935-a3b7-5787d7a65827",
  "token_type": "bearer",
  "refresh_token": "4baea735-3c0d-4dfd-b826-91c6772a0962",
  "expires_in": 36931,
  "scope": "web"
}
  • 訪問Swagger接口頁面,點擊Authorize接口進行認證,在彈出框中輸入Bearer 36034ff7-7eea-4935-a3b7-5787d7a65827並點擊認證按鈕。

  • 在Swagger中正常請求接口

通過以上幾步能夠看到接口請求會默認帶上認證參數,小夥伴們又能夠愉快的玩耍了!api

歡迎掃碼關注微信公衆號或 我的博客
相關文章
相關標籤/搜索