Authentication
Last updated
Was this helpful?
Last updated
Was this helpful?
Odi provides build in Authentication
module based on . Module is fully configurable and extendable. Also, Authentication
is integrated with .
Controller example
Install npm package
npm install jsonwebtoken --save
Auth Service should be created, to start working with authentication in Odi application. Odi automatically extracts token from request and starts processing.
Implementation must be provided for abstract class CoreAuth
with 2 generics.
Only 2 methods must be implemented
serialize(user: User)
- will be called when user.assign(...)
called.
deserialize(decoding: Decoding)
- will be called, when user.load()
called.
To have fully typed code, you should pass your Auth Service to first Controller generic.
For interacting with user in Controller
, UserData
instance will be passed to user
property. It has only the few methods.
load(options?: DecodeOptions)
- this method decode token and pass it to deserialize(...)
method. Semantically, it should be used to load user from database.
decode(options?: DecodeOptions)
- wrapper for JWT decode. Decodes Object
from token
verify(options?: VerifyOptions)
- wrapper for JWT verify. Decodes and verofy Object
from token. Method returns [ Decoding | null, Error | null ]
assign(user: User, options?: SignOptions)
- this method encode the token and return it (as string). Custom options can be passed for encoding. user
will be passed to serialize(...)
@Auth(options?: any)
decorator can be used for protecting routes by permissions or other restrictions.
authenticate
method in AuthService
class must be overridden.
We can create an alias for @Auth(options?: any)
decorator that will be used for guarding routes. options
argument will be passed to authenticate
method.
Now, simply decorate route handler of controller with a newly created decorator.
As a result, only that has "admin"
role can access this endpoint. Otherwise, 403
status code will be send.
There is only one decorator @Auth(options?: any)
. As mentioned above, options
argument will be passed to authenticate
method.
This decorator can be applied to the method or whole controller.
Guard implementation must be provided in authenticate
method of AuthService
class.
This method has 3 arguments:
context
- request and response.
data
- user data (the same as user
field in controller).
options
- object passed in dectorator.
As you can see, authenticate
method return type is a Promise<boolean>
, so asynchronous calls are allowed (Example: database request).
But there are only 2 return values are possible - true
and false
. If the result is true
, handler will process the request, otherwise 403
status code will be send immediately without further processing
module must be installed