npm.io
0.2.0 • Published 3 years ago

@mest-fe/nestjs-sso

Licence
MIT
Version
0.2.0
Deps
6
Size
46 kB
Vulns
0
Weekly
0
Install scriptsThis package runs scripts during installation (preinstall/install/postinstall)

NestJS SSO

Common authentication SDK for internal services (NestJS project).

Installation

  1. Install package: yarn add @mest-fe/nestjs-sso
  2. Add SSOModule.forRoot() to your module imports.

Usage

Authentication

Add a decorator to any controller class or method, and the user will be authenticated before the method is called.

// controller
@MestAuth()
@Controller('/users')
export class UsersController {
}

// method
@MestAuth()
@Post('/login')
async login() {
  return 'ok'
}
Scope

Specify roles for controller classes or methods:

// Require authenticated and admin role
@MestRoleAuth(MestRoles.ADMIN)
@Delete('/users')
async removeUsers() {
  return 'ok'
}
Get current user

On any controller method, the user of the current session can be injected:

@Get('/users/self')
@MestAuth()
async getSelf(@MestUser() user: MestUserType){
  return user
}

HTTP Bearer Auth

When you just need to authenticate a fixed token, i.e. string comparison, use bearer authentication mode:

// module
HttpBearerModule.forRoot({ token: 'my-token' })

// controller
@Get('/token')
@MestTokenAuth()
async getMessage() {
  return `hello world`
}

// fetch('...', { headers: { Authorization: 'Bearer my-token' }}>

Errors

When a user without a session request an api that requires authentication, a 401 error will be returned in http; If the user simply has a role that does not match, a 403 error will be thrown.

The server will not handle these errors and you should direct the user on the client side to the sso.mest.sh to log in.