Swagger整合Oauth2


 

如果項目中使用了Oauth2.0,那么在每次請求接口的時候都需要在header上帶上Authorization參數才可以正常訪問,如下所示:

項目用了Swagger在線接口文檔組件,那么如何結合Oauth2.0,讓調用接口的時候自動帶上認證參數呢?

以下就是Oauth2.0整合Swagger的步驟:

關鍵代碼

@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/token
{
  "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中正常請求接口

經過以上幾步可以看到接口請求會默認帶上認證參數,小伙伴們又可以愉快的玩耍了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM