0

Hi am using Swager APi with nodejs. I am new to this technology. i was facing issue in my code. Tried to implement JWT token auth but unfortunately i was stuck and don't know how to over come this issue. i was getting 403 error. I have added my code and error below . so please let me know if anyone know it.

Swagger.yml

swagger: "2.0"
info:
  version: "0.0.1"
  title: Movie DB
# during dev, should point to your local machine
host: localhost:8000
# basePath prefixes all resource paths 
basePath: /
# 
schemes:
  # tip: remove http to make production-grade
  - http
  - https
# format of bodies a client can send (Content-Type)
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header

consumes:
  - application/json
  - text/html
# format of the responses to the client (Accepts)
produces:
  - application/json
paths:
  /movies:
    # binds a127 app logic to a route
    x-swagger-router-controller: movies
    get:
      security:
        - Bearer: []
      x-security-scopes:
      - admin
      description: Returns 'Hello' to the caller
      # used as the method name of the controller
      operationId: index
      parameters:
        - name: name
          in: query
          description: The name of the person to whom to say hello
          required: false
          type: string
      responses:
        "200":
          description: Success
          schema:
            # a pointer to a definition
            $ref: "#/definitions/MovieListBody"
        # responses may fall through to errors
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
    post:
      description: Creates a new movie entry
      operationId: create
      parameters:
        - name: movie
          required: true
          in: body
          description: a new movie details
          schema:
            $ref: "#/definitions/MovieBody"
      responses:
        "200":
          description: a successfully stored movie details
          schema:
            $ref: "#/definitions/MovieBody"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"

  /movies/{id}:
    x-swagger-router-controller: movies
    get:
      description: get movie
      operationId: show
      parameters:
        - name: id
          required: true
          in: path
          description: get particular movie details
          type: string
      responses:
        "200":
          description: Sucess
          schema:
            $ref: "#/definitions/MovieBody"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"

    put:
      description: Update Movie
      operationId: update
      parameters:
        - name: id
          required: true
          in: path
          type: string
        - name: movie
          required: true
          in: body
          description: an updated movie details
          schema:
            $ref: "#/definitions/MovieBody"
      responses:
        "200":
          description: Sucess
          schema:
            $ref: "#/definitions/MovieBody"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"


    delete:
      description: Delete Single Record
      operationId: deleted
      parameters:
        - name: id
          required: true
          in: path
          description: remove single record in db
          type: string
      responses:
        "200":
          description: Sucess
          schema:
            $ref: "#/definitions/MovieBody"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"

  /login:
    x-swagger-router-controller: movies
    post:
      description: Get Jwt Authentication Token
      operationId: login
      parameters:
        - name: Userdetails
          required: true
          in: body
          description: Jwt Auth token
          schema:
            $ref: "#/definitions/LoginBody"
      responses:
        "200":
          description: Sucess
          schema:
            $ref: "#/definitions/LoginBody"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"





definitions:
  MovieListBody:
    required:
      - movies
    properties:
      movies:
        type: array
        items:
          $ref: "#/definitions/Movie"

  Movie:
    required:
      - title
      - gener
      - year
    properties:
      title:
        type: string
      gener:
        type: string
      year:
        type: integer


  Login:
    required:
      - id
      - name
      - company
    properties:
      id:
        type: integer
      name:
        type: string
      company:
        type: string


  MovieBody:
    required:
      - movies
    properties:
      movies:
          $ref: "#/definitions/Movie"

  LoginBody:
    required:
      - details
    properties:
      details:
          $ref: "#/definitions/Login"


  ErrorResponse:
    required:
      - message
    properties:
      message:
        type: string

Controller.js

'use strict';

var Movie = require('../models/movies')
var MongoClient = require('mongodb').MongoClient;
var jwt = require('jsonwebtoken')
const redis = require('redis');



const client = redis.createClient()
client.on('connect', function () {
    console.log('Redis client connected');
});

client.on('error', function (err) {
    console.log('Something went wrong ' + err);
});

var db;


module.exports = {index, create, show, update, deleted};


//Get Method:
function index(req,res,next)
{
    console.log("hai")
    var token = VerifyToken(req,res,next)
    jwt.verify(req.token, 'secretkey', (err, authdata) => {
        if (err) {
            console.log(err)
        }
        else {
            client.hgetall('products', (err, results) => {
                if (results) {
                    res.send(results)
                }
                else {
                    db.collection('Ecommerce').find(30).toArray((err, results) => {
                        const ttl = 0
                        client.hmset('products', results, ttl)

                        res.send(results)
                    });
                }
            })
            // db.collection('Ecommerce').find().toArray( (err, results) => {
            //     res.send(results)
            //   });
        }
    })
}

//Post Method:
function create(req,res,next)
{
    var movie = res.json(req.body)
        //res.json(movie)
        db.collection('Ecommerce').save(movie, (err, result) => {
            if (err) return console.log(err)

            res.send("Inserted Scessfully")
        })
}


//Get Particulardata
function show(req,res,next)
{
    var number = parseInt(req.swagger.params.id.value)
       db.collection('Ecommerce').find({ "id":number}).toArray((err, result) => {
           console.log(result)
        res.send(result)
    })   
}

//Update Method
function update(req,res,next)
{
    var number = parseInt(req.swagger.params.id.value)
        db.collection("Ecommerce").update({ "id": number }, { $set: { 'title': req.body.movies.title } }, (err, result) => {
            res.send('user updated sucessfully');
        });
}


//Delete Method
function deleted(req,res,next)
{
    var number = parseInt(req.swagger.params.id.value)
        db.collection('Ecommerce').deleteOne({ "id": number }, (err, result) => {


        });
}


//Login Method
function login(req,res,next)
{
    const user = req.body.details
    jwt.sign({ user }, 'secretkey', { expiresIn: '30m' }, (err, token) => {
        res.json({ token })
        console.log({ token })
    })

}

Facing Issue

{
  "message": "unknown security handler: Bearer",
  "code": "server_error",
  "statusCode": 403
}

1 Answer 1

0

A bit old but in case it can help others, I believe your security definition is wrongly configured.

According to the Swagger documentation about Bearer authentication, you should use the following configuration:

securityDefinitions:
  bearerAuth:
    type: http
    scheme: bearer
    bearerFormat: JWT
Sign up to request clarification or add additional context in comments.

2 Comments

This isn't working for me. I get an error message: Unknown security definition type http
This is not working with Open API 2.0 or swagger 2.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.