triauth for Express
JavaScript web server - a complete sign-in flow in about 30 lines.
- Library
- triauth-js
- Install
npm install triauth express express-session- Needs
- A server-side session to hold the challenge
Get started
Express is the minimalist web framework for Node.js. You can add “Sign in with triauth” to your Express application with the official triauth-js library and express-session to keep the challenge between the two steps.
Install
npm install triauth express express-sessionA complete application
const Triauth = require('triauth');
const express = require('express');
const session = require('express-session');
const crypto = require('crypto');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(session({secret: crypto.randomBytes(64).toString('hex')})); // replace with your own secret
app.get('/', (req, res) => {
const errorMessage = req.session.error?.message || '';
req.session.error = null;
res.send(`
<form action="/login" method="post">
<input type="text" name="identifier" placeholder="Enter your identifier">
<span style="color:red;">${errorMessage}</span>
<input type="submit" value="Sign in with triauth">
</form>
`);
});
app.post('/login', async (req, res) => {
const identifier = req.body.identifier;
// Demo only: in production replace with your own static URL
// Do not trust req.headers.host unless it is validated by your reverse proxy/framework config.
const callbackUrl = `${req.protocol}://${req.headers.host}/callback`;
const authResult = await Triauth.authenticate({
identifier,
callbackUrl
});
if (authResult.challenge && authResult.redirectUrl) {
req.session.challenge = authResult.challenge;
res.redirect(302, authResult.redirectUrl);
} else {
req.session.error = authResult.error;
res.redirect(302, '/');
}
});
app.post('/callback', async (req, res) => {
const challenge = req.session.challenge;
const response = req.body.response;
delete req.session.challenge;
const authResult = await Triauth.authenticate({
challenge,
response
});
if (authResult.authenticated) {
res.send(`Logged in as ${authResult.identifier}`);
} else {
req.session.error = authResult.error;
res.redirect(302, '/');
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});Three things the example gets right, and your app should too: the challenge is stored server-side and never read from the request, it is deleted before the second call regardless of the outcome, and the callback URL is not derived from user input in production.
All logos and trademarks belong to their respective owners and do not imply affiliation or endorsement of the organization or product by triauth, nor vice versa. The content provided on this page may include information from third-party sources. We do not assume any responsibility for the completeness, correctness, or applicability of the information. You should independently verify any details before relying on them.