天天看點

Swagger整合Oauth2

如果項目中使用了Oauth2.0,那麼在每次請求接口的時候都需要在header上帶上

Authorization

參數才可以正常通路,如下所示:
Swagger整合Oauth2

項目用了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","[email protected]"))
                .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整合Oauth2
  • 在Swagger中正常請求接口
Swagger整合Oauth2

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

繼續閱讀