Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i integrate JWT Authentication in this boiler plate #225

Open
hamzamumtaz007 opened this issue Feb 2, 2021 · 2 comments
Open

How can i integrate JWT Authentication in this boiler plate #225

hamzamumtaz007 opened this issue Feb 2, 2021 · 2 comments

Comments

@hamzamumtaz007
Copy link

I want to integrate jwt authentication in this boiler plate, also can someone help me give an overview of this in detail? How everything works?

@lixaotec
Copy link

lixaotec commented Feb 2, 2021

+1

@shkangr
Copy link

shkangr commented May 6, 2021

You can use JWT for authentication in this boilerplate by change src/auth/authorizationChecker.ts files

In my case, I add "BearerTokenMiddleware.ts" in directory /src/api/middlewares/
using npm "@bukalapak/express-bearer-token "

this is my code

import * as express from 'express'
import bearertoken from '@bukalapak/express-bearer-token'
import { ExpressMiddlewareInterface, Middleware } from 'routing-controllers'

@Middleware({ type: 'before' })
export class BearerTokenMiddleware implements ExpressMiddlewareInterface {
  use(
    req: express.Request,
    res: express.Response,
    next: express.NextFunction
  ): any {
    return bearertoken()(req, res, next)
  }
}

and then you can get jwt in request.token

now you have to change some codes in authorizationChecker.ts

in my case

export const authorizationChecker = (): ((
  action: Action,
  roles: any[]
) => Promise<boolean> | boolean) => {
  const userService = Container.get<UserService>(UserService)
  const authService = Container.get<AuthService>(AuthService)

  return async (action: Action, roles: string[]): Promise<boolean> => {

    // token text is in action.request.token
    const token = action.request.token

    // pareseFromRequest -> logic that verify jwt by your own secret key
    const { userInfo } = authService.parseFromRequest(token)

    // if got some errors in token or in select user, have to response errors

   // if you set request.user like this you can get currentUser by using "currentUser" in "routing-controllers" 
    action.request.user = await userService
      .findOne({ where: { ...conditions } })

    return true
  }
}

Hope that my comment can help you anyway

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants