Skip to content

JavaScript SDK

Integrate USSO with JavaScript/TypeScript applications.

Installation

npm install jsonwebtoken jwks-rsa

Token Verification

const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');

const client = jwksClient({
    jwksUri: 'http://localhost:8000/.well-known/jwks.json'
});

function getKey(header, callback) {
    client.getSigningKey(header.kid, (err, key) => {
        const signingKey = key.publicKey || key.rsaPublicKey;
        callback(null, signingKey);
    });
}

function verifyToken(token) {
    return new Promise((resolve, reject) => {
        jwt.verify(token, getKey, {
            audience: 'your-app',
            issuer: 'http://localhost:8000'
        }, (err, decoded) => {
            if (err) reject(err);
            else resolve(decoded);
        });
    });
}

Express Middleware

const express = require('express');
const app = express();

async function authenticator(req, res, next) {
    try {
        const token = req.headers.authorization?.split(' ')[1];
        if (!token) {
            return res.status(401).json({error: 'No token provided'});
        }

        const user = await verifyToken(token);
        req.user = user;
        next();
    } catch (error) {
        res.status(401).json({error: 'Invalid token'});
    }
}

app.get('/protected', authenticator, (req, res) => {
    res.json({user: req.user});
});

React Example

import { useState, useEffect } from 'react';

function useAuth() {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const token = localStorage.getItem('access_token');
        if (token) {
            fetch('http://localhost:8000/api/sso/v1/me', {
                headers: {'Authorization': `Bearer ${token}`}
            })
            .then(res => res.json())
            .then(setUser)
            .finally(() => setLoading(false));
        } else {
            setLoading(false);
        }
    }, []);

    const login = async (email, password) => {
        const response = await fetch('http://localhost:8000/api/sso/v1/auth/login', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({identifier: email, secret: password})
        });

        const data = await response.json();
        localStorage.setItem('access_token', data.access_token);
        setUser(data.user);
    };

    const logout = () => {
        localStorage.removeItem('access_token');
        setUser(null);
    };

    return {user, loading, login, logout};
}