使用OAuth 2.0 URL生成令牌时,如何配置SwaggerUI在标题上正确设置承载令牌?

时间:2019-09-18 14:58:52

标签: java-8 oauth-2.0 swagger-2.0 apigee bearer-token

我已设置Swagger 2配置以连接到我们的OAuth2访问令牌URL。
使用Apigee URL进行连接时,它可以毫无问题地连接到URL,但是当我执行POST请求时,出现Invalid access token错误。 (请参见下面的堆栈跟踪)

我已经使用curl验证了URL,客户端ID和密码,并且可以正常工作。而且我已经验证了,当我在curl POST命令中使用提供的令牌-H "Authorization: Bearer ********token*********"时,它可以正常工作。

但是,似乎我没有正确配置Swagger来创建“ Bearer”标头,因为它没有出现在swagger中显示的curl命令中

通过Swagger授权后:

enter image description here

用于生成令牌的手动卷曲命令:

curl -k -v -X POST -u *****************:*************** -d "grant_type=client_credentials" https://***********************/oauth/accesstoken

访问令牌响应正文:

{
  "refresh_token_expires_in" : "0",
  "api_product_list" : "[********, ********]",
  "api_product_list_json" : [ "********", "********" ],
  "organization_name" : "********",
  "developer.email" : "********",
  "token_type" : "BearerToken",
  "issued_at" : "********",
  "client_id" : "************************",
  "access_token" : "************************",
  "application_name" : "********-****-****-****-********",
  "scope" : "",
  "expires_in" : "1799",
  "refresh_count" : "0",
  "status" : "approved"
}

成功的手动卷曲命令访问端点:

curl -k -v -X POST "https://*********************/start" -H "accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer *****************" -d "{}"

swagger生成的失败的卷曲命令:

curl -X POST "https://*********************/start" -H "accept: application/json" -H "Content-Type: application/json" -d "{}"

Swagger错误消息:

{
  "fault": {
    "faultstring": "Invalid access token",
    "detail": {
      "errorcode": "oauth.v2.InvalidAccessToken"
    }
  }
}

POM.xml:

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Swagger配置:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger.host:}")
    private String swaggerHost;

    @Value("${swagger.basePath:}")
    private String swaggerBasePath;

    @Value("${swagger.oauth2.security.schema:oauth2}")
    private String securitySchemaOAuth2;

    @Value("${swagger.oauth2.token.request.url:}")
    private String oauthTokenRequestURL;

    @Autowired
    ServletContext servletContext;

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .host(swaggerHost)
                .pathProvider(new RelativePathProvider(servletContext) {

                    @Override
                    public String getApplicationBasePath() {
                        return swaggerBasePath;
                    }
                })
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                .securitySchemes(Collections.singletonList(oauth()))
                .securityContexts(Collections.singletonList(securityContext()))
                .useDefaultResponseMessages(false);
    }

    private OAuth oauth() {
        List<AuthorizationScope> authorizationScopeList = new ArrayList<>();

        List<GrantType> grantTypes = new ArrayList<>();
        GrantType creGrant = new ClientCredentialsGrant(oauthTokenRequestURL);

        grantTypes.add(creGrant);

        return new OAuth("oauth2schema", authorizationScopeList, grantTypes);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Blah")
                .description("Blah")
                .version("2019.0.1")
                .contact(new Contact("Blah", "", ""))
                .build();
    }

    private SecurityContext securityContext() {
        return SecurityContext
                .builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }

    private List<SecurityReference> defaultAuth() {

        final AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        final AuthorizationScope[] authorizationScopes = new AuthorizationScope[] { authorizationScope };

        return Collections.singletonList(new SecurityReference(securitySchemaOAuth2, authorizationScopes));
    }
}

0 个答案:

没有答案