---
title: "React, Vue or Angular: use the session in your routes"
description: "Read the Block-Auth user in your backend to protect routes and check roles."
url: "/sdk-integration-spa-session/"
language: "en"
guide: "React, Vue, Angular (+ backend)"
step: "More options, optional"
---

# Use the session in your routes

Optional. Do it when your backend needs to know who the user is: to protect routes, check roles or join Block-Auth with your own login.

> How you add the backend login routes: this page covers “With the Block-Auth package” or “My own implementation”. Both variants are written out below, each one marked. Follow only the one that matches the app.

> Your app today: this page covers “It already has a login” or “It has no login”. Both variants are written out below, each one marked. Follow only the one that matches the app.

## Use the session in your routes

### How you add the backend login routes: With the Block-Auth package.

### Your app today: It already has a login.

Your usual login stays the same. What changes is how your backend knows who the user is: it can come from your session or from Block-Auth. If the user is [linked](/sdk-integration-spa-extras.md#link-users), Block-Auth gives you their id in your app as `externalId`. Use a single function for both paths. Use it instead of your current check, also in the route your frontend calls to ask who is signed in (`GET /api/auth/me` in the example). Change `userId` to the key where your login keeps the user, and `findUser` to your own lookup:

**Node.js · Your server · next to your routes**

```javascript
import { expressSessionStore } from '@block-auth.io/node/express'

async function currentAppUser(req) {
  if (req.session.userId) return findUser(req.session.userId)
  const user = await routes.currentUser({ session: expressSessionStore(req) })
  return user?.externalId ? findUser(user.externalId) : null
}

app.get('/api/auth/me', async (req, res) => {
  const user = await currentAppUser(req)
  return user ? res.json(user) : res.status(401).end()
})
```

**PHP · Your PHP · where you handle your routes**

```php
function currentAppUser(BlockAuthRoutes $routes): ?array
{
    if (isset($_SESSION['user_id'])) {
        return findUser($_SESSION['user_id']);
    }
    $user = $routes->currentUser();
    return $user !== null && $user['externalId'] !== null ? findUser($user['externalId']) : null;
}
```

**Python (Flask) · Your Flask app · next to your routes**

```python
from flask import session
from blockauth_sdk.routes.flask import session_store

def current_app_user():
    if "user_id" in session:
        return find_user(session["user_id"])
    user = routes.current_user(session_store())
    return find_user(user["externalId"]) if user and user["externalId"] else None
```

**Python (FastAPI) · Your FastAPI app · next to your routes**

```python
from fastapi import Request
from blockauth_sdk.routes.fastapi import session_store

def current_app_user(request: Request):
    if "user_id" in request.session:
        return find_user(request.session["user_id"])
    user = routes.current_user(session_store(request))
    return find_user(user["externalId"]) if user and user["externalId"] else None
```

**.NET · Program.cs · next to your endpoints**

```csharp
async Task<AppUser?> CurrentAppUserAsync(HttpContext http, UserStore users)
{
    var ownId = http.User.FindFirstValue(ClaimTypes.NameIdentifier);
    if (ownId is not null) return await users.FindAsync(ownId);
    var user = await http.GetBlockAuthUserAsync();
    return user?.ExternalId is { } externalId ? await users.FindAsync(externalId) : null;
}
```

> **Placeholders in this code:**
>
> - `findUser` is yours: replace it with your app’s own function (your database, your cache…).
> - `find_user` is yours: replace it with your app’s own function (your database, your cache…).

**Unlinked users.** Whoever signs in with Block-Auth without being linked has a Block-Auth session, but that function returns `null` for them. Pick what to do: create an account in your app right then, or reject them so only linked users get in. To reject them, add this option to the `BlockAuthRoutes` from [step 2](/sdk-integration-spa-backend.md#add-to-server):

**Node.js · Your server · the BlockAuthRoutes from step 2**

```javascript
export const routes = new BlockAuthRoutes({
  apiKey: process.env.BLOCKAUTH_API_KEY,
  apiSecret: process.env.BLOCKAUTH_API_SECRET,
  appUrl: process.env.APP_URL,
  onLogin: (user) => (user.externalId ? undefined : false),
})
```

**PHP · Your PHP · the BlockAuthRoutes from step 2**

```php
$routes = new BlockAuthRoutes(getenv('BLOCKAUTH_API_KEY'), getenv('BLOCKAUTH_API_SECRET'), [
    'appUrl' => getenv('APP_URL'),
    'onLogin' => fn (array $user) => $user['externalId'] !== null ? null : false,
]);
```

**Python · Your app · the BlockAuthRoutes from step 2**

```python
routes = BlockAuthRoutes(
    os.environ["BLOCKAUTH_API_KEY"],
    os.environ["BLOCKAUTH_API_SECRET"],
    app_url=os.environ["APP_URL"],
    on_login=lambda user: None if user["externalId"] else False,
)
```

**.NET · Program.cs · the AddBlockAuth from step 2**

```csharp
builder.Services.AddBlockAuth(options =>
{
    options.ApiKey = builder.Configuration["BLOCKAUTH_API_KEY"]!;
    options.ApiSecret = builder.Configuration["BLOCKAUTH_API_SECRET"]!;
    options.AppUrl = builder.Configuration["APP_URL"];
    options.AuthorizeLogin = (user, _) => Task.FromResult(user.ExternalId is not null);
});
```

The rest of this section (roles and protected routes) is the same for your app.

From now on, the session is the source of truth. Read the user before doing anything that needs a signed-in user or a role. You get `null` when there is no session, it expired or it was [closed by a webhook](/sdk-integration-spa-webhooks.md):

**Node.js · Your server · next to your routes**

```javascript
import { expressSessionStore } from '@block-auth.io/node/express'

const currentUser = (req) => routes.currentUser({ session: expressSessionStore(req) })

const requireRole = (slug) => async (req, res, next) => {
  const user = await currentUser(req)
  if (!user) return res.status(401).end()
  if (!user.roles.some((role) => role.slug === slug)) return res.status(403).end()
  next()
}

app.delete('/api/orders/:id', requireRole('acme-x7k2p9'), deleteOrder)
```

**PHP · Your PHP · where you handle your routes**

```php
$user = $routes->currentUser();
if ($user === null) {
    http_response_code(401);
    exit;
}

$isAdmin = in_array('acme-x7k2p9', array_column($user['roles'], 'slug'), true);
```

**Python (Flask) · Your Flask app · next to your routes**

```python
from flask import abort
from blockauth_sdk.routes.flask import session_store

@app.delete("/api/orders/<order_id>")
def delete_order(order_id):
    user = routes.current_user(session_store())
    if user is None:
        abort(401)
    if not any(role["slug"] == "acme-x7k2p9" for role in user["roles"]):
        abort(403)
    return remove_order(order_id)
```

**Python (FastAPI) · Your FastAPI app · next to your routes**

```python
from fastapi import HTTPException, Request
from blockauth_sdk.routes.fastapi import session_store

@app.delete("/api/orders/{order_id}")
def delete_order(order_id: str, request: Request):
    user = routes.current_user(session_store(request))
    if user is None:
        raise HTTPException(401)
    if not any(role["slug"] == "acme-x7k2p9" for role in user["roles"]):
        raise HTTPException(403)
    return remove_order(order_id)
```

**.NET · Program.cs · next to your endpoints**

```csharp
app.MapGet("/api/orders", async (HttpContext http) =>
{
    var user = await http.GetBlockAuthUserAsync();
    return user is null ? Results.Unauthorized() : Results.Ok(ListOrders(user.Address));
});

app.MapDelete("/api/orders/{id}", (string id) => DeleteOrder(id))
    .RequireAuthorization(policy => policy.AddAuthenticationSchemes("BlockAuth").RequireRole("acme-x7k2p9"));
```

> **Placeholders in this code:**
>
> - Replace `acme-x7k2p9` with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name.
> - `deleteOrder` is yours: replace it with your app’s own function (your database, your cache…).
> - `remove_order` is yours: replace it with your app’s own function (your database, your cache…).
> - `ListOrders`, `DeleteOrder` are yours: replace them with your app’s own functions (your database, your cache…).

The user has `address`, `did`, `roles` (`{ name, slug }`), `externalId` (your user ID, if [linked](/sdk-integration-spa-extras.md#link-users)), `loggedInAt`, `expiresAt` (Unix seconds) and `data`. In .NET the roles are also role claims with the role slug. Use the role **slug**, not the name: see [Roles](/sdk-roles.md).

To keep your own data in the session, or to refuse a login, add `onLogin(user)`: return an object to save it as `data`, or `false` to reject the user (they are also signed out of Block-Auth). In .NET, `AuthorizeLogin` decides and `OnLogin` returns the data. `onLogout(user)` runs when the user logs out.

### How you add the backend login routes: My own implementation.

From now on, your backend session is the source of truth. Protect your own routes by reading it:

**Node.js · Your server · next to your routes**

```javascript
const requireUser = (req, res, next) => (currentUser(req) ? next() : res.status(401).end())
const requireRole = (slug) => (req, res, next) =>
  currentUser(req)?.roles.some((role) => role.slug === slug) ? next() : res.status(403).end()

app.get('/api/orders', requireUser, listOrders)
app.delete('/api/orders/:id', requireRole('acme-x7k2p9'), deleteOrder)
```

> **Placeholders in this code:**
>
> - Replace `acme-x7k2p9` with the slug of one of your roles: copy it from the Roles tab in the Dashboard, under the role name.
> - `listOrders`, `deleteOrder` are yours: replace them with your app’s own functions (your database, your cache…).
