Login
Add the login routes to your server and the links to your pages.
Add the login routes
These routes go on your server: the backend that receives your app’s requests. If you don’t have one yet, create a web server in your language; expand the folded parts of the examples and you have a complete one. Add these four routes. The callback URL (/blockauth/callback) must be on your validated domain.
| Route | Does |
|---|---|
GET /blockauth/login | Creates a random state, keeps it in the session and redirects to the Block-Auth login |
GET /blockauth/callback | Checks the state, redeems the code and creates your session. If the user rejected the login, it arrives with error=access_denied: back to your login |
GET /api/me | Returns the signed-in user, or 401 |
POST /blockauth/logout | Closes the Block-Auth sessions and yours |
The examples show what you need from Block-Auth: the client, the session helpers and the four routes. The generic parts, like the session options, are folded (⋯): if you already have a server, keep yours as they are; your session must cover these routes.
Two things the example takes for granted, and that aren’t green because your app usually has them already. Check that you have them:
- Your router: the example routes its own way (in PHP, with
if ($route === …)). If your app already has a router, add the routes to it. - The session open before these routes: the login keeps the
statein the session and the callback reads it. If your app opens the session only when it needs it, open it before these routes too (in PHP,session_start()).
Copyimport crypto from 'node:crypto'
import express from 'express'
import session from 'express-session'
Copyimport { AuthCodeClient } from '@block-auth.io/node'
Copyconst { APP_URL, BLOCKAUTH_API_KEY, BLOCKAUTH_API_SECRET, SESSION_SECRET } = process.env
Copyexport const blockauth = new AuthCodeClient(BLOCKAUTH_API_KEY, BLOCKAUTH_API_SECRET)
const sessionUser = (user) => ({
address: user.address,
roles: user.roles,
expiresAt: Date.parse(`${user.signedExpiredAt.replace(' ', 'T')}Z`),
})
export const currentUser = (req) => {
const user = req.session.user
if (user && Date.now() < user.expiresAt) return user
delete req.session.user
return null
}
export const app = express()
app.use(
session({
⋯ Generic example (4 lines)Hide generic example secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax', secure: APP_URL.startsWith('https') },
}),
)
Copyconst CALLBACK_URL = `${APP_URL}/blockauth/callback`
app.get('/blockauth/login', async (req, res) => {
const state = crypto.randomBytes(16).toString('hex')
req.session.oauthState = state
try {
const { url } = await blockauth.authorize(CALLBACK_URL, state)
res.redirect(url)
} catch {
res.redirect('/login?error=blockauth')
}
})
app.get('/blockauth/callback', async (req, res) => {
const { code, state, error } = req.query
const expected = req.session.oauthState
delete req.session.oauthState
if (!expected || state !== expected) {
return res.redirect('/login?error=invalid_state')
}
if (error === 'access_denied') return res.redirect('/login?error=access_denied')
if (typeof code !== 'string') return res.redirect('/login?error=blockauth')
try {
const user = await blockauth.exchangeCode(code, CALLBACK_URL)
req.session.regenerate((err) => {
if (err) return res.redirect('/login?error=session')
req.session.user = sessionUser(user)
res.redirect('/')
})
} catch {
res.redirect('/login?error=blockauth')
}
})
app.get('/api/me', (req, res) => {
const user = currentUser(req)
if (!user) return res.status(401).json({ error: 'unauthenticated' })
res.json({ address: user.address, roles: user.roles })
})
app.post('/blockauth/logout', async (req, res) => {
const user = req.session.user
if (user) await blockauth.signOut(user.address).catch(() => {})
req.session.destroy(() => res.redirect('/'))
})
app.listen(4000)
The app.listen(…) port is the Backend port from your data. If your server already starts, keep your own listen.
The state protects your callback against CSRF: always check it before
redeeming the code. The login link must be opened within 5 minutes, and the
code is valid for 60 seconds and only once. All the parameters are in User
login.
Your session ends when the user's Block-Auth signature does: signedExpiredAt, in UTC with the format YYYY-MM-DD HH:mm:ss. That's why the session keeps that moment and every route checks it before trusting the user (how long a session lasts).
Add the links to your pages
In your templates, the login is a plain link and the logout a form. To know who is signed in, read your session (or call GET /api/me from your scripts).
HTML
<a href="/blockauth/login">Sign in with Block-Auth</a>
<form method="post" action="/blockauth/logout">
<button type="submit">Sign out</button>
</form>
Try it
Start your app with the .env variables in the environment and open http://localhost:5173/blockauth/login. Sign in and check that you come back signed in and that GET /api/me returns your user.
If so, it works in development. The last step is Go live: the same, with your production keys and domain.

