developer tip

'Authorization : Bearer'를 어떻게 표현할 수 있습니까?

copycodes 2020. 9. 1. 07:37
반응형

'Authorization : Bearer'를 어떻게 표현할 수 있습니까? 'Swagger 사양 (swagger.json)


인증 / 보안 체계에 다음과 같이 헤더를 설정해야 함을 전달하려고합니다.

Authorization: Bearer <token>

이것이 내가 swagger 문서를 기반으로 한 것입니다 .

securityDefinitions:
  APIKey:
    type: apiKey
    name: Authorization
    in: header
security:
  - APIKey: []

도움이 될 수 있습니다.

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'

http://editor.swagger.io/#/ 에서 복사하여 붙여 넣어 결과를 확인할 수 있습니다.

또한 사용자에게 도움이 될 수있는보다 복잡한 보안 구성이 포함 된 swagger 편집기 웹의 몇 가지 예가 있습니다.


OpenAPI 3.0.0의 베어러 인증

이제 OpenAPI 3.0 은 기본적으로 Bearer / JWT 인증을 지원합니다. 다음과 같이 정의됩니다.

openapi: 3.0.0
...

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT  # optional, for documentation purposes only

security:
  - bearerAuth: []

이것은 Swagger UI 3.4.0+ 및 Swagger Editor 3.1.12+에서 지원됩니다 (다시 OpenAPI 3.0 사양에만 해당됩니다!).

UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx header.

Adding Authorization header programmatically (Swagger UI 3.x)

If you use Swagger UI and, for some reason, need to add the Authorization header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor. This solution is for Swagger UI 3.x; UI 2.x used a different technique.

// index.html

const ui = SwaggerUIBundle({
  url: "http://your.server.com/swagger.json",
  ...

  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer xxxxxxx"
    return req
  }
})

Why "Accepted Answer" works... but it wasn't enough for me

This works in the specification. At least swagger-tools (version 0.10.1) validates it as a valid.

But if you are using other tools like swagger-codegen (version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:

this.authentications = {
  'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};

There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:

this.rootGet = function(callback) { ... }

This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.

My alternative

Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.

Note: which is being discussed in

So, it's handle authentication like a standard header. On path object append an header paremeter:

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: localhost
schemes:
  - http
  - https
paths:
  /:
    get:
      parameters:
        - 
          name: authorization
          in: header
          type: string
          required: true
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

This will generate a client with a new parameter on method signature:

this.rootGet = function(authorization, callback) {
  // ...
  var headerParams = {
    'authorization': authorization
  };
  // ...
}

To use this method in the right way, just pass the "full string"

// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);

And works.

참고URL : https://stackoverflow.com/questions/32910065/how-can-i-represent-authorization-bearer-token-in-a-swagger-spec-swagger-j

반응형