CXF Swagger2功能增加了安全性 [英] CXF Swagger2Feature adding securityDefinitions

查看:115
本文介绍了CXF Swagger2功能增加了安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用org.apache.cxf.jaxrs.swagger.Swagger2Feature将Security Definition添加到我的rest服务中。但是,我看不到任何相关的方法或有关如何执行此操作的任何资源。以下是我想使用swagger2feature生成的swagger文档。我该怎么办?

I want to add Security Definition to my rest service using org.apache.cxf.jaxrs.swagger.Swagger2Feature. However I can not see any related method or any resource on how to do it. Below is the swagger doc which I want to generate using swagger2feature. How can I do it?

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
paths:
  /:
    get:
      security:
        - Bearer: []
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'


推荐答案

我遇到了同样的问题而且我找不到使用CXF及其API的合适解决方案。我的解决方案如下,创建一个扩展CXF的Swagger2Feature的类以覆盖addSwaggerResource方法,以绑定安全定义:

I was facing the same problem and I couldn't find a suitable solution with CXF and its api. My solution is the following, create a class that extends the Swagger2Feature of CXF in order to override the addSwaggerResource method, to bound the security definition:

/** Name of the security definition */
public static final String SECURITY_NAME = "Bearer";

/** Extends the Swagger2Feature to use the security definition of Swagger */
@Provider(value = Provider.Type.Feature, scope = Provider.Scope.Server)
public class ExtendedSwagger2Feature extends Swagger2Feature {
    @Override
    protected void addSwaggerResource(Server server, Bus bus) {
        super.addSwaggerResource(server, bus);

        BeanConfig config = (BeanConfig) ScannerFactory.getScanner();
        Swagger swagger = config.getSwagger();
        swagger.securityDefinition(SECURITY_NAME, new ApiKeyAuthDefinition("authorization", In.HEADER));
    }
}

然后,作为 Swagger 实例被swagger api加载后已被修改,您应该在servlet上下文中重新注册它(据我浏览swagger代码时所了解的)。看看 io.swagger.jaxrs.config.SwaggerContextService 。为此,我必须在servlet上下文中创建一个新的 ServletContextInitializer

Then, as the Swagger instance has been modified after it has been loaded by the swagger api, you should "re-register" it in the context of the servlet (as I understand when I browsed the code of swagger). Have a look at io.swagger.jaxrs.config.SwaggerContextService. To do this, I had to create a new ServletContextInitializer in my servlet context:

return servletContext -> {
    BeanConfig scanner = (BeanConfig) ScannerFactory.getScanner();
    Swagger swagger = scanner.getSwagger();
    servletContext.setAttribute("swagger", swagger);
};

将先前使用安全性定义修改过的 Swagger 配置放入上下文昂扬的api才能正确考虑它。没有这个,我们扩展的Swagger2Feature将无法正常工作。

Putting in the context the Swagger configuration previously modified with the security definition allows the swagger api to take it into account correctly. Without this, our extended Swagger2Feature would not work.

通过这一更改,我能够像您期望的那样获得一个swagger.yaml文件,尤其是以下部分:

With this changes, I was able to get a swagger.yaml file as the one you are expecting, especially the following part:

securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header

我正在Spring Boot应用程序中使用此解决方案,这是我完整的配置类,以防它对某人有所帮助:

I am using this solution in a Spring Boot application, here is my complete swagger configuration class, in case it helps someone:

package my.package.configuration;

import io.swagger.config.ScannerFactory;
import io.swagger.core.filter.AbstractSpecFilter;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.model.ApiDescription;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.auth.ApiKeyAuthDefinition;
import io.swagger.models.auth.In;
import org.apache.cxf.Bus;
import org.apache.cxf.annotations.Provider;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.List;
import java.util.Map;

/**
 * Configuration of the Swagger API to enable it with CXF.
 */
@Configuration
public class SwaggerConfiguration {

    /** Name of the security definition */
    public static final String SECURITY_NAME = "Bearer";

    @Bean
    public Swagger2Feature swagger() {
        Swagger2Feature feature = new ExtendedSwagger2Feature();
        // Do your stuff with the configuration
        return feature;
    }

    /**
     * Register a custom {@link ServletContextInitializer} in the cxf servlet to expose the custom {@link Swagger2Feature}
     * otherwise the security definition added in the {@link ExtendedSwagger2Feature#addSwaggerResource} will not be
     * used by the swagger api because the original hook occurs during the super call.
     *
     * @see io.swagger.jaxrs.config.SwaggerContextService
     * @see org.apache.cxf.jaxrs.spring.SpringComponentScanServer
     *
     * @return a new instance of the {@link ServletContextInitializer}
     */
    @Bean
    @DependsOn("jaxRsServer")
    public ServletContextInitializer initializer() {
        return servletContext -> {
            BeanConfig scanner = (BeanConfig) ScannerFactory.getScanner();
            Swagger swagger = scanner.getSwagger();
            servletContext.setAttribute("swagger", swagger);
        };
    }

    /**
     * Extension of the {@link Swagger2Feature} because the one provided by CXF doesn't allow to use
     * feature of the Swagger API such as the security definition. This feature use the {@link ApiKeyAuthDefinition}
     * to transport the authorization header required by the application.
     */
    @Provider(value = Provider.Type.Feature, scope = Provider.Scope.Server)
    public static class ExtendedSwagger2Feature extends Swagger2Feature {
        @Override
        protected void addSwaggerResource(Server server, Bus bus) {
            super.addSwaggerResource(server, bus);

            BeanConfig config = (BeanConfig) ScannerFactory.getScanner();
            Swagger swagger = config.getSwagger();
            swagger.securityDefinition(SECURITY_NAME, new ApiKeyAuthDefinition("authorization", In.HEADER));
        }
    }
}

这篇关于CXF Swagger2功能增加了安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆