swagger-ui icon indicating copy to clipboard operation
swagger-ui copied to clipboard

Swagger-UI refuses to add request header

Open jaman1020 opened this issue 11 years ago • 41 comments

I've been pulling my hair out on this, not sure if I'm doing something wrong? I have been unable to get a swagger-ui request to include ANY type of header. My Grape API uses an API token in the header for auth, and no matter what I do I cannot get it to show up in anything. I've tried all of the api-key example code, so I must be doing SOMETHING wrong.

However, upon closer inspection, even the demo petstore app does not contain an api header in the request headers.

screen shot 2015-05-06 at 2 52 21 am

I'm using the readme/sample code verbatim right now -

function addApiKeyAuthorization(){
        var key = encodeURIComponent($('#input_apiKey')[0].value);
        if(key && key.trim() != "") {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
            window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
            log("added key " + key);
        }
      }

How can I get a request header of "api_key: value" to show up in request headers?

jaman1020 avatar May 06 '15 09:05 jaman1020

That's probably because of a known bug. Can you try the develop_2.0 branch?

webron avatar May 06 '15 10:05 webron

Just tried it and the same thing happened. Here is the relevant code in index.html -

      function addApiKeyAuthorization(){
        var key = encodeURIComponent($('#input_apiKey')[0].value);
        if(key && key.trim() != "") {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
            window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
            log("added key " + key);
        }
      }

      $('#input_apiKey').change(addApiKeyAuthorization);

      // if you have an apiKey you would like to pre-populate on the page for demonstration purposes...

        var apiKey = "myApiKeyXXXX123456789";
        $('#input_apiKey').val(apiKey);
        addApiKeyAuthorization();

and the request headers - screen shot 2015-05-06 at 3 21 36 am

I've also tried changing apiKeyAuth to 'header' instead of query, no dice

jaman1020 avatar May 06 '15 10:05 jaman1020

Yes, a legacy line has been causing some hair-loss. We've removed a dead line that caused confusion... https://github.com/swagger-api/swagger-ui/issues/1205 Try after removing that line(s), and if it's still not working - I'll try and replicate.

ponelat avatar May 06 '15 10:05 ponelat

That fixed the initial crash I was having, but unfortunately still didn't add a header. I'm inspecting the request both on the chrome side and grape side and there's nothing in either

jaman1020 avatar May 06 '15 10:05 jaman1020

Ok, I'm going to replicate. You're using the readme example, from develop_2.0?

ponelat avatar May 06 '15 10:05 ponelat

The key in the example is a "query" key, meaning it gets attached to url?api_key=some-key. It looks like it's working on develop_2.0 Try changing "

var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
// to this...
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "header"); // <- make it a header key

ponelat avatar May 06 '15 10:05 ponelat

We currently support "query" and "header" auth keys, although there is a mechanism to manipulate each request before it gets executed, meaning you can have access to all headers, parameters, etc. Which is a little more "hands on" though. You should see the request header, if you change the above - I'm testing it with Google Chromes' Network tab.

ponelat avatar May 06 '15 11:05 ponelat

Not sure what I'm doing wrong, but I still can't see it. I downloaded the develop_2.0 branch and opened ./dist/index.html in chrome. I haven't changed anything but this line in the whole project. This is the entire contents of the script tag -

  <script type="text/javascript">
    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://petstore.swagger.io/v2/swagger.json";
      }
      window.swaggerUi = new SwaggerUi({
        url: url,
        dom_id: "swagger-ui-container",
        supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
        onComplete: function(swaggerApi, 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)
          });

          addApiKeyAuthorization();
        },
        onFailure: function(data) {
          log("Unable to Load SwaggerUI");
        },
        docExpansion: "none",
        sorter : "alpha"
      });

      function addApiKeyAuthorization(){
        var key = encodeURIComponent($('#input_apiKey')[0].value);
        if(key && key.trim() != "") {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "header");
            window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
            log("added key " + key);
        }
      }

      $('#input_apiKey').change(addApiKeyAuthorization);

      // if you have an apiKey you would like to pre-populate on the page for demonstration purposes...

        var apiKey = "myApiKeyXXXX123456789";
        $('#input_apiKey').val(apiKey);


      window.swaggerUi.load();

      function log() {
        if ('console' in window) {
          console.log.apply(console, arguments);
        }
      }
  });
  </script>

and this is what I see in Chrome's tab when I click explore -

Remote Address:[::1]:9292
Request URL:http://localhost:9292/v1
Request Method:GET
Status Code:401 Unauthorized
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin:null
Access-Control-Expose-Headers:
Access-Control-Max-Age:1728000
Connection:Keep-Alive
Content-Length:27
Content-Type:application/json
Date:Wed, 06 May 2015 10:59:46 GMT
Server:WEBrick/1.3.1 (Ruby/2.1.2/2014-05-08)
Vary:Origin
Request Headers
view source
accept:application/json;charset=utf-8,*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:9292
Origin:null
Pragma:no-cache
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36

jaman1020 avatar May 06 '15 11:05 jaman1020

Are you trying to use an api_key to access your spec? ...I've been looking at executing operations (eg: GET /pet).

ponelat avatar May 06 '15 11:05 ponelat

I was...I just whitelisted the swagger url and everything loaded...doh I did, however, get a Uncaught TypeError: Cannot read property 'undefined' of undefined error after it loaded. I think I remember seeing that in another issue? stacktrace if helpful -

Uncaught TypeError: Cannot read property 'undefined' of undefined
9.Operation.resolveModel    @   index.js:248
9.module.exports    @   index.js:131
(anonymous function)    @   spec-converter.js:38
arrayEach   @   binaryIndex.js:28
65.module.exports   @   mergeData.js:45
(anonymous function)    @   spec-converter.js:18
61.module.exports   @   isLaziable.js:13
baseForOwn  @   createFind.js:24
60.module.exports   @   isIndex.js:1
65.module.exports   @   mergeData.js:46
3.SwaggerClient.buildFromSpec   @   spec-converter.js:12
6.Resolver.resolve  @   model.js:135
(anonymous function)    @   resolver.js:218
7.SwaggerSpecConverter.finish   @   operation.js:401
7.SwaggerSpecConverter.resourceListing.http.on.response @   operation.js:275
(anonymous function)    @   spec-converter.js:508
111.Request.callback    @   index.js:24
(anonymous function)    @   index.js:24
112.Emitter.emit    @   index.js:24
111.Request.end.xhr.onreadystatechange  @   index.js:24

jaman1020 avatar May 06 '15 11:05 jaman1020

Sorry, I'm back (so is github) Hmm, undefined of undefined - ain't that a pickle. I'm not familiar with the issue (probably is out there) but this looks like an unguarded variable reference.

Could be an error in the spec, that's causing this ugly error. Which isn't very friendly at all. If you like I can take a look at the spec, otherwise... try validating it with swagger-tools. To get you going. This is an issue in the error reporting at the very least, but it may be related to the spec.

ponelat avatar May 06 '15 12:05 ponelat

Otherwise, you can share your definition with us and we'll try to find the problem.

webron avatar May 06 '15 12:05 webron

Anything new concerning the missing headers?

ifig avatar May 21 '15 14:05 ifig

think this is related?

https://github.com/domaindrivendev/Swashbuckle/issues/353

I'm changing my request type from json to xml and it's not returning an error and just kicking back those javascript errors in the chrome console.

don't mean to hijack but seems related so maybe this will help.

mrtristan avatar May 22 '15 04:05 mrtristan

@mrtristan - completely unrelated.

webron avatar May 22 '15 04:05 webron

hey @ifig, I don't think there is an actual issue with missing headers... but if you'd like to, you can show us your spec and we can see if anything sticks out. @jaman1020 how goes your quest for API heaven?

ponelat avatar May 22 '15 05:05 ponelat

Well, I thought it was the same problem as described before : I want to request the url where my swagger specs are defined, but for that, I need to add a token in the header when I change the api key. I added the following lines, but I can't see that header going in the request.

$('#input_apiKey').change(function() {
  var key = $('#input_apiKey')[0].value;
  if(key && key.trim() != "") {
    swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("api_key", key, "header"));
  }
})

ifig avatar May 22 '15 07:05 ifig

@ifig if you're hiding the spec itself behind an auth layer, take a look at this comment... https://github.com/swagger-api/swagger-ui/issues/1171#issuecomment-100374999 Does that helps clarify things?

ponelat avatar May 22 '15 07:05 ponelat

Well, I have no idea of what happened, but I forked again the UI from github and now I can see the headers passing through... That's really weird though. Another question but I shouldn't probably ask it in this thread : is there a way to pass a token in the headers just to access the documentation (that's what I do for now), and then pass a different token in the headers for each route I test?

ifig avatar May 22 '15 08:05 ifig

Yup, I believe that's possible. It's not an area I'm familiar with... here is the spec reference .. https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#security-requirement-object

and you can put it on the operation level... https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operation-object

ponelat avatar May 22 '15 08:05 ponelat