swagger-api / swagger-core

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API
http://swagger.io
Apache License 2.0
7.37k stars 2.17k forks source link

Swagger core 1.3.9 - can't seem to get authentication working. #685

Closed lagrwilson closed 9 years ago

lagrwilson commented 9 years ago

I want to be able to authenticate and set permissions for each api.

I have a list of about 20 permissions. I want to be able to pass a bearer token in the header and have my authentication manage access to specific apis.

I upgraded to Swagger core, jaxrs and annotations to version 1.3.9.

I added the following lines to my api, and it won't even compile.

@POST
@Timed
@Logged
@Produces({MediaType.APPLICATION_JSON})
@ApiEndpointPermissions({
        @ApiEndpointPermission(permission = PermissionStrings.ORGANIZATION_READ,
                permissionInstancePathParam = PathParamNames.ORGANIZATION_ID),
        @ApiEndpointPermission(permission = PermissionStrings.API_KEY_CREATE)
})
@ApiOperation(value = "Create Api Keys",
        consumes = MediaType.APPLICATION_JSON,
        authorizations = Array(new Authorization(value="oauth2",
                scopes = Array(
                        new AuthorizationScope(scope = "organization:read", description = "read organization"),
                        new AuthorizationScope(scope = "apikey:create", description = "create apiKey")
                ))))
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "Bad Request"),
        @ApiResponse(code = 403, message = "Credentials are required to access this resource")
})

public ApiKeyResponse createApiKey(@PathParam(PathParamNames.ORGANIZATION_ID) OrganizationId organizationId,
                                   @Context HttpServletRequest request) {

   // Do stuff here.
    return apiKeyResponse;
}

My index.html in my swaggerui resource changed to so that api-key goes on header rather than query.

I have several issues:

I've checked the how to embed oauth2 blog post and that post is really old, out of date and there don't seem to be equivalent functions. So I can't pass the api-key in the header with my bearer token and have swagger connect to get the proper permissions to exercise the apis.

Please provide some guidance on authenticating my apis within swagger's documentation. I am using Java 1.8, dropwizard.

Thank you. Lucille Wilson

I can't seem to add annotations to the apis to document the permissions each api is allowed.

I can't seem to hook up oath2 at all.

lagrwilson commented 9 years ago

Hi. I've been talking with my team. We've simplified our expectations of what the use case will be. What we would like to do is have our developers use Swagger UI to test our rest apis. Our rest apis rely on authentication and permissions. So when the developer uses the Try it Out button, we want to pass a request header named Authorization and the value will be "Bearer" + "APIKEYTOKENHERE". So the request header will equal "Authorization" = "Bearer APIKEYTOKENHERE". Do you have any advice on how to include a request header?

webron commented 9 years ago

https://github.com/wordnik/swagger-ui#custom-header-parameters---for-basic-auth-etc

lagrwilson commented 9 years ago

Just this one line in index.html? I'll let you know how this goes this afternoon.

On Wed, Sep 24, 2014 at 10:05 AM, webron notifications@github.com wrote:

https://github.com/wordnik/swagger-ui#custom-header-parameters---for-basic-auth-etc

— Reply to this email directly or view it on GitHub https://github.com/wordnik/swagger-core/issues/685#issuecomment-56674298 .

lagrwilson commented 9 years ago

Success! Here is what I did in Swagger core and Swagger UI for version 1.3.9.

  1. Swagger's index.html, while inside the script tag, I changed the lines containing the url and the window.authorizations.add()
  <script type="text/javascript">
    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = url[1];
      } else {
        url = "http://localhost:9090/service/api-docs";
      }
      window.swaggerUi = new SwaggerUi({
      url: url,
      dom_id: "swagger-ui-container",
      supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
      onComplete: function(swaggerApi, swaggerUi){
        log("Loaded SwaggerUI");

        if(typeof initOAuth == "function") {
          /*
          initOAuth({
            clientId: "your-client-id",
            realm: "your-realms",
            appName: "your-app-name"
          });
         */
        }
        $('pre code').each(function(i, e) {
          hljs.highlightBlock(e)
        });
      },
      onFailure: function(data) {
        log("Unable to Load SwaggerUI");
      },
      docExpansion: "none",
      sorter : "alpha"
    });

    $('#input_apiKey').change(function() {
      var key = $('#input_apiKey')[0].value;
      log("key: " + key);
      if(key && key.trim() != "") {
        log("added key " + key);
        window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "Bearer d2da3376-aa85-44e7-9be6-2c80b615d25b", "header"));
      }
    })
    window.swaggerUi.load();
  });
  </script>
``
2. I added swaggerui as a resource in my project.  Inside of the swaggerui directory I included an api-docs file and a listings folder containing a file which described one api resource.  (this step is optional)
api-docs:
```json
    {
        "apiVersion":"1.3.9",
        "swaggerVersion":"1.2",
      "apis":[
           {
              "path":"http://localhost:9090/swaggerui/listings/orgs-apiKey",
              "description":"3.x ApiKey APIs"
           },
         ]
     }

// listings/orgs-apiKey

{
   "apiVersion":"1.3.9",
   "swaggerVersion":"1.2",
   "basePath":"http://localhost:9090/service",
   "resourcePath":"/3.0/orgs/{orgId}/apiKeys",
   "apis":[
      // etc.
}
  1. In my Resource file I add the swagger annotations:
@Api(value = "/3.0/orgs/{orgId}/apiKeys", description = "3.x API Key APIs")
   @ApiOperation(value = "Get Api Keys")
    @ApiResponses(value = {
            @ApiResponse(code = 400, message = "Bad Request"),
            @ApiResponse(code = 403, message = "Credentials are required to access this resource")
    })
  1. Maven:
In my maven pom file I added:
       <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-core_2.10</artifactId>
            <version>1.3.9</version>
        </dependency>
        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-jaxrs_2.10</artifactId>
            <version>1.3.9</version>
        </dependency>
        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.3.9</version>
        </dependency>
  1. In my DropWizard application start up class:
        environment.jersey().register(new ApiListingResourceJSON());

        // Swagger providers
        environment.jersey().register(new ApiDeclarationProvider());
        environment.jersey().register(new ResourceListingProvider());

        // Swagger Scanner, which finds all the resources for @Api Annotations
        ScannerFactory.setScanner(new DefaultJaxrsScanner());

        // Add the reader, which scans the resources and extracts the resource information
        ClassReaders.setReader(new DefaultJaxrsApiReader());

        // Set the swagger config options
        SwaggerConfig config = ConfigFactory.config();
        config.setApiVersion("1.3.9");
        config.setBasePath("http://localhost:9090/service");
  1. When I run my application, I can go to http://localhost:9090/swaggerui/index.html Then I put my string "Bearer d2da3376-aa85-44e7-9be6-2c80b615d25b" in the text box next to the url text box and hit the Explore button. Then I go to ApiKey Rest API of mine and I submit the Try it Out button and the resource allows the Authorization Bearer credential and returns data from my application.
webron commented 9 years ago

Can we close the issue then?

lagrwilson commented 9 years ago

Sure, as long as you agree with my explanation. Thank you for your help. Lucille

On Wed, Sep 24, 2014 at 4:25 PM, webron notifications@github.com wrote:

Can we close the issue then?

— Reply to this email directly or view it on GitHub https://github.com/wordnik/swagger-core/issues/685#issuecomment-56732939 .

fehguy commented 9 years ago

thank you for the explanation, i'll get this added to our documentation.

webron commented 9 years ago

Can't find anything specific that requires documentation. @lagrwilson if there's anything you feel is missing, please add a comment.