Skip to content

Restricting endpoint access

Agustín Borrego edited this page Dec 6, 2022 · 1 revision

Access to individual endpoints can be restricted on an is-logged or has-role basis. The way to prove authorization is to send a session token when trying to access a restricted endpoint, through an HTTP Token header.

Restrict access to logged users

All endpoint definitions accept an optional auth_required argument that can be set to true if the endpoint is intended to be used only by logged users:

"create":{
  "route": "/departments",
  "method": "POST",
  "sql": "INSERT INTO departments(name, city) VALUES ($name, $city)",
  "auth_required": true, <------
  "description": "Creates a new Department",
  "request_body_params": ["name", "city"]
}

When an endpoint is protected in this manner, the user has to prove that they have a current session by sending their session token as an HTTP header, under the key Token:

GET /api/departments
Token: .eJwl[...]WKXc

(200 OK)
[
  {
    "departmentId": 1,
    "city": "Manchester",
    "name": "Artificial Ingelligence"
  },
  {
    "departmentId": 2,
    "city": "Seville",
    "name": "Computer Systems"
  }
]

Session tokens are provided by the /register and /login endpoints under the "sessionToken" response field, and they remain valid for the duration specified in the MAX_TOKEN_AGE setting. If the user tries to access a restricted endpoint without providing a valid session token, the server responds with a 401 HTTP code:

GET /api/departments
(No "Token" header)

(401 UNAUTHORIZED)
{
  "code": 401,
  "message": "Unauthorized"
}

Restricting access to certain user roles

Silence allows for a more fine-grained restriction of endpoints, allowing only users with certain roles to use them. To enable this behavior, you must configure the role attribute of the USER_AUTH_DATA configuration parameter in settings.py so that it contains the name of the column that stores the role in your users table. For example:

USER_AUTH_DATA = {
    "table": "Users",
    "identifier": "username",
    "password": "password",
    "role": "userRole",
}

Then, you can add an aditional allowed_roles parameter to you endpoint, whose value will be a list of all roles that can use the endpoint:

"create":{
  "route": "/departments",
  "method": "POST",
  "sql": "INSERT INTO departments(name, city) VALUES ($name, $city)",
  "auth_required": true,
  "allowed_roles": ["Manager", "Director"], <------
  "description": "Creates a new Department",
  "request_body_params": ["name", "city"]
}

Note that you must use a list even if you want to restrict it to a single role. If you do not specify a list of allowed roles, a default value of ["*"] is assumed, meaning that all logged users can access the endpoint.

Just like in the previous example, to use a restricted endpoint, the user must provide their access token as a request header.