Auth0 oauth for micro
Add Auth0 authentication to your micro service as easy as a flick of your fingers. This module is meant to be used like a module from microauth collection.
npm install --save microauth-auth0
# or
yarn add microauth-auth0
Take your credentials from the settings section in the Auth0 dashboard :
Setting | value example | configuration |
---|---|---|
Allowed Callback URLs: | 'http://localhost:3000/auth/auth0/callback' | callbackUrl |
Domain: | 'your-domain.auth0.com' | domain |
Client ID: | 'your-client-id' | clientId |
Client Secret: | 'your-client-secret' | clientSecret |
connections | 'database' | connection |
APIs | 'http://nomeOfApi/' | audience |
scopes | 'openid email address phone profile' | scope |
state parameter | false | noState |
basic Auth | false | basicAuth |
auth forward ip | false | send_ip |
algorithm | 'RS256' | algorithm |
Post Username and Password direct | false | allowPost |
database connection | 'database' | realm |
native app | true | PKCE |
'prompt=none' parameter | true | silentPrompt |
when discovering host and protocol | true | trustProxy |
not check these paths | ['/imagine/(.*)','/wth/'] | whitelist |
path to login redirect | '/auth/auth0/' | path |
app.js
const send = require('micro').send;
const microAuthAuth0 = require('.');
require('dotenv-safe').config();
const options = {
domain: process.env.AUTH0_DOMAIN,
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
callbackUrl: process.env.AUTH0_CALLBACKURL, // 'http://localhost:3000/auth/auth0/callback'
connection: null, // Forces the user to sign in with a specific connection
path: '/auth/auth0',
scope: 'openid email address phone profile offline_access'
// profile scope = name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated_at
};
const auth0 = microAuthAuth0(options);
// Third `auth` argument will provide error or result of authentication
// so it will { err: errorObject} or { result: {
// provider: 'auth0',
// accessToken: 'blahblah',
// tokens: {all tokens and related information}
// info : {
// user : {data from /userinfo endpoint}
// apiToken : {decoded access jwt token}
// idToken : {decoded token id}
// }}}
const handler = async (req, res, auth) => {
if (!auth) {
return send(res, 404, 'Not Found');
}
if (auth.err) {
// Error handler
console.error(auth.err);
return send(res, 403, 'Forbidden');
}
// Save something in database here
return `Hello ${auth.result.info.user.nickname} !`;
};
module.exports = auth0(handler);
Run:
micro app.js
Now visit http://localhost:3000/auth/auth0