Swagger,JWT,如何在认证后在调用中使用令牌

时间:2016-07-07 17:04:22

标签: swagger

我是个新招摇的人 我们已经编写了一个API,因此我尝试手动编写swagger.yaml

到目前为止,我已经想出如何进行我的/登录路线..并在响应中找回JWT。
但我不知道下一步该怎样走 是否可以自动将返回的JWT插入后续调用中? 或者我是否必须手动复制并粘贴返回的JWT?

如果我必须手动做..然后..呃......怎么样? 在swagger编辑器中出现一个Authenticate按钮,我可以点击它并获得一个输入框来查找apikey ...
但是在查看swagger UI时它不一样...当我浏览到localhost看到swagger UI我没有得到验证按钮而且没有任何地方可以粘贴JWT文本......

我的swagger.yaml如下:

swagger: "2.0"
info:
  version: 1.0.0
  title: Identity Management Service
  description: API to allow JWT authentication and authorisation
  termsOfService: http://swagger.io/terms/
  
  license:
    name: MIT
    url: http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
host: localhost:8000
basePath: /
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
consumes:
  - application/json
produces:
  - application/json
paths:
  /login:
    post:
      summary: User Authentication returning a JWT.
      description: Authenticate a user.
      parameters:
        - name: credentials
          in: body
          description: maximum number of results to return
          required: false
          schema:
            $ref: '#/definitions/creds'
      responses:
        "200":
          description: will send JWT
        default:
          description: unexpected error
          schema:
            $ref: '#/definitions/Error'
  /getUsers:
    get:
      summary: Gets list of all users
      description: Authenticate a user.
      security:
        - Bearer: []
      responses:
        "200":
          description: will send JWT
        default:
          description: unexpected error
          schema:
            $ref: '#/definitions/Error'
definitions:
  creds:
    type: object
    required:
      - username
      - password
    properties:
      username:
        type: string
      password:
        type: string

  Error:
    required:
      - code
      - message
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string

显然我更喜欢这样做,以便/ login调用中的响应令牌存储并在/ getUsers中使用...

来自/ login的调用响应如下:

{
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoidXNlciIsInVzZXJpZCI6InBqbWVhbHkiLCJlbWFpbCI6InBqbWVhbHlAZ21haWwuY29tIiwiZmlyc3RuYW1lIjoiUEoiLCJsYXN0bmFtZSI6Ik1lYWx5Iiwib3JnIjoib3JnMSIsInRlYW1zIjpbInRlYW0xIl0sImFjbCI6WyJlbXBsb3llZSIsInRlYW1MZWFkIl0sInRva2VuVHlwZSI6IndlYkFwcFRva2VuIiwidG9rZW5WZXJzaW9uIjoiMSIsImlhdCI6MTQ2NzkxMDkyNSwiZXhwIjoxNDY3OTk3MzI1fQ.e4Trk-0kDoid5Xr9BQ5ZP_HMBN2l8_G2pn7ac2tt4uE",
  "user": {
    "type": "user",
    "userid": "joebloggs",
    "email": "joe@bloggs.com",
    "firstname": "Joe",
    "lastname": "Bloggs",
    "org": "org1",
    "teams": [
      "team1"
    ],
    "acl": [
      "employee",
      "teamLead"
    ],
    "tokenType": "webAppToken",
    "tokenVersion": "1",
    "iat": 1467910925,
    "exp": 1467997325
  }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试一下,它包含一个授权标头,您可以在其中保存令牌,该标头将应用于所有端点。

@Bean
public Docket newsApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(Lists.newArrayList(apiKey()))
            .securityContexts(Lists.newArrayList(securityContext()))
            .apiInfo(generateApiInfo());
}

@Bean
SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Lists.newArrayList(
            new SecurityReference("JWT", authorizationScopes));
}

private ApiKey apiKey() {
    return new ApiKey("JWT", "Authorization", "header");
}

enter image description here enter image description here