@kaname-png/plugin-api-jwt
TypeScript icon, indicating that this package has built-in type declarations

5.0.1 • Public • Published

Neko Plugins Logo

@kaname-png/plugin-api-jwt

Plugin for @sapphire/framework to add JSON Web Tokens strategy in @sapphire/plugin-api plugin to JWT.

GitHub codecov npm (scoped) npm

Description

This plugin add the authentication system JSON Web Tokens to @sapphire/plugin-api plugin for @sapphire/framework.

This plugin does not change the behavior of the @sapphire/plugin-api plugin, so after installing the plugin you can continue to use the @sapphire/plugin-api plugin as you always have.

Features

  • Fully ready for TypeScript!
  • Includes ESM ready entrypoint
  • Easy to use

Installation

@kaname-png/plugin-api-jwt depends on the following packages. Be sure to install these along with this package!

You can use the following command to install this package, or replace npm install with your package manager of choice.

npm install @kaname-png/plugin-api-jwt @sapphire/framework @sapphire/plugin-api

Usage

JavaScript

In your main or setup file, register the plugin:

// Remember to register the API plugin first, then this plugin.
require('@sapphire/plugin-api/register');
require('@kaname-png/plugin-api-jwt/register');

Once the plugin is registered, we have to configure some options.

async function main() {
	const client = new SapphireClient({
		api: {
			auth: {
				id: 'xxx' /** client oauth id **/,
				secret: 'xxx' /** client oauth secret **/,
				redirect: 'https://kaname.netlify.app/oauth' /** client oauth redirect **/,
				jwt: {
					secret: 'uwu' /** JWT tokens are signed with this secret key. (required) **/,
					issuer: 'kaname.netlify.app' /** See https://jwt.io/introduction  (optional and by default api.auth.redirect) **/,
					algorithm: 'HS256' /**  (optional and by default HS512) **/,
					sessionsHooks: {
						/** Optional hooks for persistent sessions (optional) **/,
						get: (token, type) => {
							// Do something with your database or something else.
							// ...

							return { access_token: '<access_token>', refresh_token: '<refresh_token>' };
						},
						create: (payload) => {
							// Do something with your database or something else.
							// ...
						},
						delete: (accessToken) => {
							// Do something with your database or something else.
							// ...
						}
					}
				}
			}
		}
	});

	await client.login();
}

void main();

TypeScript

In your main or setup file, register the plugin:

// Remember to register the API plugin first, then this plugin.
import '@sapphire/plugin-api/register';
import '@kaname-png/plugin-api-jwt/register';

Once the plugin is registered, we have to configure some options.

async function main() {
	const client = new SapphireClient({
		api: {
			auth: {
				id: 'xxx' /** client oauth id **/,
				secret: 'xxx' /** client oauth secret **/,
				redirect: 'https://kaname.netlify.app/oauth' /** client oauth redirect **/,
				jwt: {
					secret: 'uwu' /** JWT tokens are signed with this secret key. (required) **/,
					issuer: 'kaname.netlify.app' /** See https://jwt.io/introduction  (optional and by default api.auth.redirect) **/,
					algorithm: 'HS256' /**  (optional and by default HS512) **/,
					sessionsHooks: {
						/** Optional hooks for persistent sessions (optional) **/,
						get: (token, type) => {
							// Do something with your database or something else.
							// ...

							return { access_token: '<access_token>', refresh_token: '<refresh_token>' };
						},
						create: (payload) => {
							// Do something with your database or something else.
							// ...
						},
						delete: (accessToken) => {
							// Do something with your database or something else.
							// ...
						}
					}
				}
			}
		}
	});

	await client.login();
}

void main();

How to use

Now, when you log in you will get a response like this, where the authentication token is attached.

Remember that the authentication token must be in the authorization header with the value: Bearer [ token here ].

{
	"user": {
		"auth": {
			// See https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-response
		},
		"data": {
			"id": "858367536240394259",
			"username": "kaname-png",
			"avatar": "28f2ec4eec159df460dc9b58f2a80318",
			"discriminator": "1751",
			"public_flags": 0,
			"flags": 0,
			"banner": null,
			"banner_color": null,
			"accent_color": null,
			"verified": true
		}
	},
	"access_token": "eyJhbGciOiJIUzI1NiJ9.XXXXX",
	"refresh_token": "eyJhbGciOiJIUzI1NiJ9.XXXXX"
}

You can get the token information on a route, middleware, etc. in the following way:

Javascript

const { methods, Route } = require('@sapphire/plugin-api');

class UserRoute extends Route {
	constructor(context, options) {
		super(context, {
			...options,
			route: 'user/route'
		});
	}

	[methods.GET](request, response) {
		const session = request.session;
		response.json({ session });
	}
}

exports.default = UserRoute;

Typescript

import { ApiResponse, methods, Route } from '@sapphire/plugin-api';
import type { ApiRequest } from '@kaname-png/plugin-api-jwt';

export class UserRoute extends Route {
	constructor(context: Route.Context, options: Route.Options) {
		super(context, {
			...options,
			route: 'user/route'
		});
	}

	[methods.GET](request: ApiRequest, response: ApiResponse) {
		const session = request.session;
		response.json({ session });
	}
}

It is important to remember that if the authorization token is invalid, then the _request.auth variable will be null.

And as mentioned in the description, this plugin does not change the way @sapphire/plugin-api plugin is used, so you can follow the @sapphire/plugin-api plugin documentation.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Kaname

💻 🐛 📖 🚇 🚧 👀

This project follows the all-contributors specification. Contributions of any kind welcome!

Package Sidebar

Install

npm i @kaname-png/plugin-api-jwt

Weekly Downloads

34

Version

5.0.1

License

MIT

Unpacked Size

102 kB

Total Files

48

Last publish

Collaborators

  • kaname-png