JWT-checking decorator for typescript-rest
npm install typescript-rest-jwt-guardshell
$ npm i typescript-rest-jwt-guard
`
Or using yarn:
`shell
$ yarn add typescript-rest-jwt-guard
`
Preconditions
As soon as the decorators retrieve tokens from request context, you have to provide context as dependency injection to your wrapped methods:
`ts
@JwtCookieGuard('BEARER')
@GET
public myMethod(@Context _context: ServiceContext) {
return { message: 'Ok' };
}
`
You must also ensure that process.env.JWT_SECRET environment variable contains JWT secret.
Usage with cookies
If access token is supposed to be passed with cookies, you must provide cookie parser:
`ts
app.use(cookieParser());
`
Now you can use decorators in your methods:
`ts
import { Path, GET, Context, ServiceContext } from 'typescript-rest';
import { Inject } from 'typescript-ioc';
import { JwtCookieGuard } from 'typescript-rest-jwt-guard';@Path('/test')
export default class DemoController {
@JwtCookieGuard('BEARER')
@Path('/cookie-jwt')
@GET
public getHealthStatusSecured(@Context _context: ServiceContext) {
return { message: 'Ok' };
}
}
`
Now requests to that route must provide a cookie with name BEARER and the JWT token as its value.
Usage with authorization header
If access token is supposed to be passed with authorization header, you can use JwtHeaderGuard like this:
`ts
import { Path, GET, Context, ServiceContext } from 'typescript-rest';
import { Inject } from 'typescript-ioc';
import { JwtHeaderGuard } from 'typescript-rest-jwt-guard';@Path('/test')
export default class DemoController {
@JwtHeaderGuard('Bearer')
@Path('/header-jwt')
@GET
public getHealthStatusSecured(@Context _context: ServiceContext) {
return { message: 'Ok' };
}
}
`
Now all requests to that route must provide authorization header with value 'Bearer X' where X is the JWT access token.
Usage with POST request body data
If access token is supposed to be passed with POST body data, you must provide body parser:
`ts
app.use(bodyParser.json());
`
Now you can use decorators in your methods:
`ts
import { Path, POST, Context, ServiceContext } from 'typescript-rest';
import { Inject } from 'typescript-ioc';
import { JwtBodyGuard } from 'typescript-rest-jwt-guard';@Path('/test')
export default class DemoController {
@JwtBodyGuard('accessToken')
@Path('/body-jwt')
@POST
public getHealthStatusSecured(@Context _context: ServiceContext) {
return { message: 'Ok' };
}
}
``