Add sign-in to your app
Working code for the authorization code flow with PKCE in a browser, a mobile app and on your server.
Web app
A browser app holds no secret. It creates a one-time verifier, sends the person to MaxwellTrack, and exchanges the returned code with that verifier.
const ISSUER = "https://maxwelltrack.com/api/oauth";
const CLIENT_ID = "mt_your_client_id";
const REDIRECT_URI = window.location.origin + "/callback";
const b64url = (bytes) =>
btoa(String.fromCharCode(...new Uint8Array(bytes)))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
// 1. Send the person to MaxwellTrack
export async function signIn() {
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
const state = b64url(crypto.getRandomValues(new Uint8Array(16)));
sessionStorage.setItem("mt_verifier", verifier);
sessionStorage.setItem("mt_state", state);
location.href = "https://maxwelltrack.com/oauth/authorize?" + new URLSearchParams({
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
response_type: "code",
scope: "openid profile email",
state,
code_challenge: challenge,
code_challenge_method: "S256",
});
}
// 2. On your callback page, exchange the code
export async function handleCallback() {
const params = new URLSearchParams(location.search);
if (params.get("state") !== sessionStorage.getItem("mt_state")) {
throw new Error("This sign-in did not start here.");
}
const res = await fetch(ISSUER + "/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
grant_type: "authorization_code",
client_id: CLIENT_ID,
code: params.get("code"),
redirect_uri: REDIRECT_URI,
code_verifier: sessionStorage.getItem("mt_verifier"),
}),
});
sessionStorage.removeItem("mt_verifier");
sessionStorage.removeItem("mt_state");
if (!res.ok) throw new Error((await res.json()).error_description);
return res.json(); // { access_token, id_token, refresh_token, ... }
}Mobile app
// npx expo install expo-auth-session expo-crypto
import { useEffect } from "react";
import { Button } from "react-native";
import * as AuthSession from "expo-auth-session";
const CLIENT_ID = "mt_your_client_id";
export function SignInButton() {
const discovery = AuthSession.useAutoDiscovery("https://maxwelltrack.com/api/oauth");
const redirectUri = AuthSession.makeRedirectUri({
scheme: "examplefleet", // the scheme you registered
path: "oauth/callback",
});
const [request, response, promptAsync] = AuthSession.useAuthRequest(
{ clientId: CLIENT_ID, redirectUri, scopes: ["openid", "profile", "email"], usePKCE: true },
discovery,
);
useEffect(() => {
if (response?.type !== "success" || !discovery || !request?.codeVerifier) return;
AuthSession.exchangeCodeAsync(
{
clientId: CLIENT_ID,
code: response.params.code,
redirectUri,
extraParams: { code_verifier: request.codeVerifier },
},
discovery,
).then((tokens) => {
// tokens.accessToken, tokens.idToken, tokens.refreshToken
});
}, [response, discovery, request, redirectUri]);
return <Button title="Continue with MaxwellTrack" disabled={!request} onPress={() => promptAsync()} />;
}Verify tokens on your server
Tokens are signed with a private key and checked against the published public keys, so your server can confirm a token is genuine without calling MaxwellTrack on every request.
// npm install jose
import { createRemoteJWKSet, jwtVerify } from "jose";
const ISSUER = "https://maxwelltrack.com/api/oauth";
const keys = createRemoteJWKSet(new URL(ISSUER + "/jwks.json")); // cached, refreshed on rotation
export async function verifyIdToken(idToken) {
const { payload } = await jwtVerify(idToken, keys, {
issuer: ISSUER,
audience: "mt_your_client_id",
});
return payload; // payload.sub is the account's permanent id
}Read the profile
curl "https://maxwelltrack.com/api/oauth/userinfo" \
-H "Authorization: Bearer ACCESS_TOKEN"The answer holds only the claims covered by the scopes the person approved.
Something unclear or out of date on this page? Tell support.
