oauth
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.
Viewing readonly version of main branch: v159View latest version
OAuth authentication middleware for Val Town vals.
- OAuth 2.0 Authorization Code flow with PKCE
- Dynamic client registration
- Encrypted session cookies (stateless)
- No database required
/** @jsxImportSource https://esm.sh/hono/jsx */
import { Hono } from "https://esm.sh/hono";
import { oauthMiddleware, getOAuthUserData } from "https://esm.town/v/std/oauth/middleware";
const app = new Hono();
app.get("/", async (c) => {
const user = await getOAuthUserData(c.req.raw);
return c.html(
<html>
<body>
{user ? (
<p>Logged in as {user.username}</p>
) : (
<a href="/auth/login">Log in</a>
)}
</body>
</html>
);
});
export default oauthMiddleware(app.fetch);
Wraps your application to handle OAuth routes.
Options:
scopes?: string[]- OAuth scopes (default:["openid", "offline_access", "profile"])clientName?: string- OAuth client name
Auto-handled routes:
/auth/login- Start OAuth flow/auth/callback- OAuth callback/auth/logout- Clear session
Extract user data from session cookie.
Returns: SessionData | null
interface SessionData {
userId: string;
username: string;
accessToken: string;
refreshToken?: string;
idToken?: string;
expiresAt: number;
}
OAUTH_STATE_ENCRYPTION_KEY(optional) - Encryption key for state and sessions- Auto-generated if not set
- Set manually (e.g.,
openssl rand -base64 32) for better performance
- User clicks
/auth/login - Redirects to Val Town OAuth
- User authorizes
- Callback receives code, exchanges for tokens
- User data extracted from ID token
- Session encrypted and stored in cookie
- Use
getOAuthUserData(req)to access user data
Sessions last 30 days and are stored as encrypted cookies (no server-side storage).