Basic JWT server for Server State servers (cf. https://github.com/server-state/simple-server)
Install the server with npm install @server-state/auth-jwt-server and import it with
const JWT = require('@server-state/auth-jwt-server');JWT is now an imported class. Therefore, you can use
const jwtServer = new JWT(config);to instantiate a new instance to use with your server.
The config consists of multiple required and optional fields:
issuerName: string- the name of the token's issuer. Required for multi-server setupsgetUsersGroups: (username: string) => Promise<string[]>- a function that determines (and resolves with an array of) the user groups the passed user has access to.authenticate: (username: string, password: string) => Promise<boolean>- a function that checks users credentials. Returns aPromise<boolean>that resolves totrueif the credentials are valid andfalseif they are not.
privateKey: string- the RS256 private key. Gets generated if none is provided; If provided,publicKeybecomes a required field.publicKey: string- the RS256 public key. Gets generated if none is provided; If provided,privateKeybecomes a required field.
Use
jwt.setup(router, '/auth/jwt');where router is your express router to set up the route /auth/jwt as API endpoint for authentication (use .
This sets up
POST /auth/jwtwhich returns a JSON string of the users token on success, HTTP 401 if the credentials couldn't be verified and HTTP 400 if either username or password weren't specified in the body.
To finally use the module in your server, you need to access it in your ServerBase config's isAuthorized. This is very dependent on your personal setup, but one basic example could look something like this:
isAuthorized: (req, authorizedGroups) => {
const currentUsersGroups = jwt.getAuthorizedGroups(req.header('Authorization'));
for (const group of authorizedGroups) {
if (group === 'guest' || currentUsersGroups.includes(group)) {
return true;
}
}
return false;
}