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.

RouteDoes
GET /blockauth/loginCreates a random state, keeps it in the session and redirects to the Block-Auth login
GET /blockauth/callbackChecks 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/meReturns the signed-in user, or 401
POST /blockauth/logoutCloses 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.

server.js · where you create your Express appNew from Block-Auth
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({
    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.

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

Your template, where you want the button
<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.