---
title: "PHP, Python, .NET or Node.js: login"
description: "Add the login routes to your server and the links to your pages."
url: "/sdk-integration-server-login/"
language: "en"
guide: "PHP, Python, .NET, Node.js"
step: "Quickstart step 2 of 3, required"
---

# 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.

> **Note:** 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 `state` in 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()`).

**Node.js · server.js · where you create your Express app**

```javascript
import crypto from 'node:crypto'
import express from 'express'
import session from 'express-session'
import { AuthCodeClient } from '@block-auth.io/node'

const { APP_URL, BLOCKAUTH_API_KEY, BLOCKAUTH_API_SECRET, SESSION_SECRET } = process.env

export 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') },
  }),
)

const 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)
```

**PHP · public/index.php · your entry point**

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use BlockAuth\AuthCodeClient;
use BlockAuth\Exceptions\BlockAuthException;

$appUrl = getenv('APP_URL');

session_start([
    'cookie_httponly' => true,
    'cookie_samesite' => 'Lax',
    'cookie_secure' => str_starts_with($appUrl, 'https'),
]);

$blockauth = new AuthCodeClient(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET'));

function json(int $status, array $body): void
{
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($body);
    exit;
}

function currentUser(): ?array
{
    $user = $_SESSION['user'] ?? null;
    if ($user && time() < $user['expires_at']) {
        return $user;
    }
    unset($_SESSION['user']);
    return null;
}

$route = $_SERVER['REQUEST_METHOD'] . ' ' . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$callbackUrl = $appUrl . '/blockauth/callback';

if ($route === 'GET /blockauth/login') {
    $state = bin2hex(random_bytes(16));
    $_SESSION['oauth_state'] = $state;
    try {
        $login = $blockauth->authorize($callbackUrl, $state);
    } catch (BlockAuthException $e) {
        header('Location: /login?error=blockauth');
        exit;
    }
    header('Location: ' . $login['url']);
    exit;
}

if ($route === 'GET /blockauth/callback') {
    $expected = $_SESSION['oauth_state'] ?? null;
    unset($_SESSION['oauth_state']);
    if (!$expected || !hash_equals($expected, (string) ($_GET['state'] ?? ''))) {
        header('Location: /login?error=invalid_state');
        exit;
    }
    if (($_GET['error'] ?? '') === 'access_denied') {
        header('Location: /login?error=access_denied');
        exit;
    }
    $code = $_GET['code'] ?? null;
    if (!is_string($code)) {
        header('Location: /login?error=blockauth');
        exit;
    }
    try {
        $user = $blockauth->exchangeCode($code, $callbackUrl);
    } catch (BlockAuthException $e) {
        header('Location: /login?error=blockauth');
        exit;
    }
    session_regenerate_id(true);
    $_SESSION['user'] = [
        'address' => $user['address'],
        'roles' => $user['roles'],
        'expires_at' => strtotime($user['signedExpiredAt'] . ' UTC'),
    ];
    header('Location: /');
    exit;
}

if ($route === 'GET /api/me') {
    $user = currentUser();
    if (!$user) {
        json(401, ['error' => 'unauthenticated']);
    }
    json(200, ['address' => $user['address'], 'roles' => $user['roles']]);
}

if ($route === 'POST /blockauth/logout') {
    $user = $_SESSION['user'] ?? null;
    if ($user) {
        try {
            $blockauth->signOut($user['address']);
        } catch (BlockAuthException $e) {
        }
    }
    session_destroy();
    header('Location: /');
    exit;
}
```

**Python · app.py · where you create your app**

```python
import hmac
import os
import secrets
from datetime import datetime, timezone

from flask import Flask, jsonify, redirect, request, session
from blockauth_sdk import AuthCodeClient, BlockAuthError

APP_URL = os.environ["APP_URL"]

app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"]
app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax", SESSION_COOKIE_SECURE=APP_URL.startswith("https"))

blockauth = AuthCodeClient(os.environ["BLOCKAUTH_API_KEY"], os.environ["BLOCKAUTH_API_SECRET"])


def session_user(user):
    expires_at = datetime.strptime(user["signedExpiredAt"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
    return {"address": user["address"], "roles": user["roles"], "expires_at": expires_at.timestamp()}


def current_user():
    user = session.get("user")
    if user and datetime.now(timezone.utc).timestamp() < user["expires_at"]:
        return user
    session.pop("user", None)
    return None

CALLBACK_URL = f"{APP_URL}/blockauth/callback"


@app.get("/blockauth/login")
def login():
    state = secrets.token_hex(16)
    session["oauth_state"] = state
    try:
        url = blockauth.authorize(CALLBACK_URL, state)["url"]
    except BlockAuthError:
        return redirect("/login?error=blockauth")
    return redirect(url)


@app.get("/blockauth/callback")
def callback():
    expected = session.pop("oauth_state", None)
    code, state = request.args.get("code"), request.args.get("state", "")
    if not expected or not hmac.compare_digest(expected, state):
        return redirect("/login?error=invalid_state")
    if request.args.get("error") == "access_denied":
        return redirect("/login?error=access_denied")
    if not code:
        return redirect("/login?error=blockauth")
    try:
        user = blockauth.exchange_code(code, CALLBACK_URL)
    except BlockAuthError:
        return redirect("/login?error=blockauth")
    session.clear()
    session["user"] = session_user(user)
    return redirect("/")


@app.get("/api/me")
def api_me():
    user = current_user()
    if not user:
        return jsonify(error="unauthenticated"), 401
    return jsonify(address=user["address"], roles=user["roles"])


@app.post("/blockauth/logout")
def redirect_logout():
    user = session.get("user")
    if user:
        try:
            blockauth.sign_out(user["address"])
        except BlockAuthError:
            pass
    session.clear()
    return redirect("/")
```

**.NET · Program.cs**

```csharp
using System.Globalization;
using System.Security.Cryptography;
using System.Text.Json;
using BlockAuth;
using BlockAuth.Exceptions;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.SecurePolicy = builder.Configuration["APP_URL"]!.StartsWith("https")
        ? CookieSecurePolicy.Always
        : CookieSecurePolicy.SameAsRequest;
});
builder.Services.AddSingleton(new AuthCodeClient(
    builder.Configuration["BLOCKAUTH_API_KEY"]!,
    builder.Configuration["BLOCKAUTH_API_SECRET"]!));

var app = builder.Build();
app.UseSession();

string? CurrentAddress(HttpContext http)
{
    var expiresAt = http.Session.GetString("expires_at");
    var valid = expiresAt is not null && DateTime.ParseExact(expiresAt, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
        DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal) > DateTime.UtcNow;
    if (valid) return http.Session.GetString("address");
    http.Session.Clear();
    return null;
}

var appOrigin = new Uri(builder.Configuration["APP_URL"]!).GetLeftPart(UriPartial.Authority);

var callbackUrl = $"{appOrigin}/blockauth/callback";

app.MapGet("/blockauth/login", async (HttpContext http, AuthCodeClient blockauth) =>
{
    var state = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
    http.Session.SetString("oauth_state", state);
    try
    {
        var login = await blockauth.AuthorizeAsync(callbackUrl, state);
        return Results.Redirect(login.Url);
    }
    catch (BlockAuthException)
    {
        return Results.Redirect("/login?error=blockauth");
    }
});

app.MapGet("/blockauth/callback", async (string? code, string? state, string? error, HttpContext http, AuthCodeClient blockauth) =>
{
    var expected = http.Session.GetString("oauth_state");
    http.Session.Remove("oauth_state");
    if (expected is null || state != expected)
        return Results.Redirect("/login?error=invalid_state");
    if (error == "access_denied")
        return Results.Redirect("/login?error=access_denied");
    if (string.IsNullOrEmpty(code))
        return Results.Redirect("/login?error=blockauth");
    try
    {
        var user = await blockauth.ExchangeCodeAsync(code, callbackUrl);
        http.Session.Clear();
        http.Session.SetString("address", user.Address);
        http.Session.SetString("roles", user.Roles.GetRawText());
        http.Session.SetString("expires_at", user.SignedExpiredAt);
        return Results.Redirect("/");
    }
    catch (BlockAuthException)
    {
        return Results.Redirect("/login?error=blockauth");
    }
});

app.MapGet("/api/me", (HttpContext http) =>
{
    var address = CurrentAddress(http);
    if (address is null) return Results.Json(new { error = "unauthenticated" }, statusCode: 401);
    var roles = JsonDocument.Parse(http.Session.GetString("roles") ?? "[]").RootElement.Clone();
    return Results.Ok(new { address, roles });
});

app.MapPost("/blockauth/logout", async (HttpContext http, AuthCodeClient blockauth) =>
{
    var address = http.Session.GetString("address");
    if (address is not null)
    {
        try { await blockauth.SignOutAsync(address); } catch (BlockAuthException) { }
    }
    http.Session.Clear();
    return Results.Redirect("/");
});

app.Run();
```

> **Placeholders in this code:**
>
> - The `app.listen(…)` port is the Backend port from your data. If your server already starts, keep your own `listen`.

> **Note:** 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](/api-user-login.md).

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](/security.md#session)).

## 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**

```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 `https://your-app.com/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](/sdk-integration-server-go-live.md): the same, with your production keys and domain.

Next step: [Go live](/sdk-integration-server-go-live.md)
