---
title: "Roles"
description: "Give your users roles in the Dashboard and use them in your app: show or hide UI in the frontend and protect routes in your backend."
url: "/sdk-roles/"
language: "en"
---

# Roles

Give your users roles in the Dashboard, such as `admin` or `editor`, and use them in your app. Block-Auth sends the user's roles with every login.

## Create and assign roles

In the Dashboard, create the roles and assign them to your users. See [Dashboard roles](/dashboard-roles.md).

Each role has a **name**, which you choose and can rename, and a **slug**, which Block-Auth generates when you create the role (for example `acme-x7k2p9`) and never changes. Use the slug in your code: copy it from the **Roles** tab in the Dashboard, under the role's name.

## Show or hide UI

Once the user has logged in with the widget, read their roles in the frontend. They come from your backend's answer (`/code` and `/me` in the [backend routes](/sdk-integration-spa-backend.md#backend-routes)), so you don't need anything else.

**React**

```jsx
import { useBlockAuthUser } from '@block-auth.io/react'

export function AdminLink() {
  const { hasRoleBySlug, isLoadingUser } = useBlockAuthUser()

  if (isLoadingUser || !hasRoleBySlug('acme-x7k2p9')) return null
  return <a href="/admin">Admin panel</a>
}
```

**Vue**

```vue
<script setup>
import { useBlockAuthUser } from '@block-auth.io/vue'

const { hasRoleBySlug, isLoadingUser } = useBlockAuthUser()
</script>

<template>
  <a v-if="!isLoadingUser && hasRoleBySlug('acme-x7k2p9')" href="/admin">Admin panel</a>
</template>
```

**Angular**

```typescript
import { Component, inject } from '@angular/core'
import { BlockAuthService } from '@block-auth.io/angular'

@Component({
  selector: 'app-admin-link',
  standalone: true,
  template: `
    @if (!auth.isLoadingUser() && auth.hasRoleBySlug('acme-x7k2p9')) {
      <a href="/admin">Admin panel</a>
    }
  `,
})
export class AdminLinkComponent {
  auth = inject(BlockAuthService)
}
```

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

**Only for Angular:**

**Angular with `templateUrl`:** the examples put the HTML inside `template`. If your component has its HTML in its own file (`templateUrl`, the default in new Angular projects, like `app.ts` and `app.html`), move what's inside `template` to that `.html` file and keep the rest (`imports` and the methods) in the `.ts` file.

> **Note:** Hiding a button is not security: anyone can call your backend directly. Check the role in your backend too.

## Protect your backend

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

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

Your backend gets the roles when it redeems the login code (`/api/auth/token`) and keeps them in the user's session. Check them there before doing anything that needs a role. With the [Block-Auth package](/sdk-integration-spa-session.md#protect-routes), read the user with `currentUser`, which also ends the session at `signedExpiredAt` (in .NET the roles are role claims):

**Node.js**

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

function requireRole(slug) {
  return async (req, res, next) => {
    const user = await routes.currentUser({ session: expressSessionStore(req) })
    if (!user?.roles.some((role) => role.slug === slug)) {
      return res.status(403).json({ error: 'Forbidden' })
    }
    next()
  }
}

app.get('/api/admin/stats', requireRole('acme-x7k2p9'), getStats)
```

**PHP**

```php
function requireRole(BlockAuthRoutes $routes, string $slug): void
{
    $roles = $routes->currentUser()['roles'] ?? [];
    if (!in_array($slug, array_column($roles, 'slug'), true)) {
        http_response_code(403);
        exit;
    }
}

requireRole($routes, 'acme-x7k2p9');
```

**Python**

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

def require_role(slug):
    def decorator(view):
        @wraps(view)
        def wrapped(*args, **kwargs):
            roles = (routes.current_user(session_store()) or {}).get("roles", [])
            if not any(role["slug"] == slug for role in roles):
                abort(403)
            return view(*args, **kwargs)
        return wrapped
    return decorator

@app.get("/api/admin/stats")
@require_role("acme-x7k2p9")
def admin_stats():
    return get_stats()
```

**.NET**

```csharp
app.MapGet("/api/admin/stats", () => GetStats())
    .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.

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

Your backend gets the roles when it redeems the login code (`/api/auth/token`) and keeps them in the user's session. Check them there before doing anything that needs a role. `currentUser` (`current_user` in Python, `CurrentAddress` in .NET) is the helper from your guide's login routes, which also ends the session at `signedExpiredAt`:

**Node.js**

```js
function requireRole(slug) {
  return (req, res, next) => {
    const roles = currentUser(req)?.roles ?? []
    if (!roles.some((role) => role.slug === slug)) {
      return res.status(403).json({ error: 'Forbidden' })
    }
    next()
  }
}

app.get('/api/admin/stats', requireRole('acme-x7k2p9'), getStats)
```

**PHP**

```php
function requireRole(string $slug): void
{
    $roles = currentUser()['roles'] ?? [];
    if (!in_array($slug, array_column($roles, 'slug'), true)) {
        http_response_code(403);
        exit;
    }
}

requireRole('acme-x7k2p9');
```

**Python**

```python
from functools import wraps
from flask import abort, session

def require_role(slug):
    def decorator(view):
        @wraps(view)
        def wrapped(*args, **kwargs):
            roles = (current_user() or {}).get("roles", [])
            if not any(role["slug"] == slug for role in roles):
                abort(403)
            return view(*args, **kwargs)
        return wrapped
    return decorator

@app.get("/api/admin/stats")
@require_role("acme-x7k2p9")
def admin_stats():
    return get_stats()
```

**.NET**

```csharp
bool HasRole(HttpContext http, string slug)
{
    if (CurrentAddress(http) is null) return false;
    using var roles = JsonDocument.Parse(http.Session.GetString("roles") ?? "[]");
    return roles.RootElement.EnumerateArray()
        .Any(role => role.GetProperty("slug").GetString() == slug);
}

app.MapGet("/api/admin/stats", (HttpContext http) =>
    HasRole(http, "acme-x7k2p9") ? Results.Ok(GetStats()) : Results.StatusCode(403));
```

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

Roles are read at login. If you change a user's roles in the Dashboard, your backend sees them on the user's next login.

## Reference

`useBlockAuthUser()` in React and Vue, and the `BlockAuthService` signals in Angular, return:

| Value                                 | What it is                                                     |
| ------------------------------------- | -------------------------------------------------------------- |
| `roles`                               | The user's roles, as `{ name, slug }`.                         |
| `roleNames` / `roleSlugs`             | Only the names, or only the slugs.                             |
| `hasRoleBySlug(slug)`                 | `true` if the user has that role.                              |
| `hasAnyRoleBySlug(slugs)`             | `true` if the user has at least one of them.                   |
| `hasRole(name)` / `hasAnyRole(names)` | The same, by name. Not case-sensitive.                         |
| `isLoadingUser`                       | `true` while the user is loading. Wait for it before deciding. |
| `user`                                | The logged-in user (`address`, `did`, `roles`), or `null`.     |
