Handling Authentication
HttpServerShim
provides two major way of handling authentication and roles:
Authorization
header with Bearer tokenserver-session
cookie with token definition
Defining Authentication Handlers
Both bearer token and server session feed into customHandler
function under
server.config.security.token
config. You can define the authentication behavior
based on the authentication token given and assign corresponding roles to the
current access level.
import { Result, ok, errorResult } from 'ts-basis/nodejs'
server.config.security.token.customHandler = async (
op: HttpOp,
token: string,
): Promise<Result<boolean>> => {
if (token !== 'my_token') {
return errorResult(new Error(`Unauthorized`))
}
// e.g. if JWT token, async verify here ...
return ok(true)
}
Using ReturnCodeFamily
for Enumerated Returns
Inline errorResult
with custom Error object can also be replaced with your
custom ReturnCodeFamily
if you want to enable full enumerated returns.
import { Result, ok, errorResult, ReturnCodeFamily } from 'ts-basis/nodejs'
enum AuthenticationTokenCodeEnum {
TOKEN_NOT_RECOGNIZED,
}
export const AuthenticationTokenCode =
ReturnCodeFamily('AuthenticationTokenCode', AuthenticationTokenCodeEnum)
server.config.security.token.customHandler = async (
op: HttpOp,
token: string,
): Promise<Result<boolean>> => {
if (token !== 'my_token') {
return AuthenticationTokenCode.error('TOKEN_NOT_RECOGNIZED')
}
// e.g. if JWT token, async verify here ...
return ok(true)
}