Supported Authentication Strategies in AdonisJS

List of supported strategies

Adonis supports 4 different authentication strategies which are

  1. JSON Web Tokens (JWT)
  2. Basic and
  3. Personal API
  4. Session

Description of different strategies

JWT

The JWT strategy is token-based. It is mostly used in APIs which are extensively used in mobile and single-page apps. All authentication configuration occurs within the auth.js config file.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Basic

The basic strategy like other stateless strategies has no concept of login and logout. Every request has to be sent with the uid and password. The uid is any unique field in the users table set in the config file.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

One good thing about Adonis is its support for different auth mechanisms in a single project. If most of the project uses JWT auth, a part of it may choose to use basic auth by doing this and that. Configure the stuff to use basic auth when most other auth are session

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

API Token Auth

Assuming you want to support integrations for your adonis web service like Github does, you can use personal API tokens. In this case, it means that different services will have their own tokens which can be revoked anytime.

Session

The session strategy is the only stateful strategy among the 4. This means that it doesn’t involve the re-sending of credentials per HTTP request. The session strategy involves saving the user’s session data in cookies or a cache (like Redis). It’s the most convenient strategy because users don’t need to enter their credentials every time.

Security implications

There’s a catch to this strategy. It is prone to Cross-Site Request Forgery (CSRF). CSRF is when a malicious user creates a form on a random website that uses cookies from our website to send a malicious request such as a Delete Request. To manage CSRF on Trivial, we’ll enable it in config/shield.js

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

@adonisjs/shield is the security package that manages security. It has measures against CSRF, Cross-Site Scripting (XSS), sniffing and iframes.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);