Authentication: who is asking
Every request that reaches a resource first answers one question: who is making it? This chapter explains how rind asks that question, and how your application answers it.
In Django REST framework, the answer comes from the authentication
classes (DEFAULT_AUTHENTICATION_CLASSES): SessionAuthentication,
TokenAuthentication, simplejwt’s JWTAuthentication. Each one reads the
request and sets request.user. rind works the same way, with two
differences:
- rind itself has no user model, no passwords, no sessions and no login route. It only defines the question and the shape of the answer. Your application gives the code that answers it.
- There is one authenticator per application, not a list. When you want
several schemes, one authenticator tries them in turn (the
rind-authcrate does exactly that).
Three chapters cover users, in this order:
- This chapter, Authentication: how a request becomes a user, or nobody.
- Signing in: how users get a token in the first
place. This is the
rind-authcrate: tokens, passwords, password reset, codes by mail. It plays the part ofdjango.contrib.authanddjangorestframework-simplejwt. - Permissions: what a user may do once rind knows who they are: which actions, on which rows, seeing which fields.
A first example
The sample application (the railway, in sample/) stores a token in a
column of each user. A client sends it in the Authorization header, and
the application finds the user who has it:
#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-ops/src/lib.rs
use accounts_models::{Group, USER_GROUPS, User};
use rind::api::{ApiError, Authenticate, BoxFuture, Identity};
use rind::prelude::*;
pub struct TokenAuth;
impl Authenticate for TokenAuth {
fn authenticate<'a>(
&'a self,
db: &'a Db,
authorization: Option<&'a str>,
) -> BoxFuture<'a, Result<Option<Identity>, ApiError>> {
Box::pin(async move {
let Some(token) = authorization.and_then(|h| h.strip_prefix("Bearer ")) else {
return Ok(None);
};
let user = db
.first(&Query::<User>::new().filter(User::token().eq(token.trim())))
.await?
.ok_or(ApiError::Unauthorized)?;
let groups = db
.load_m2m(Query::<Group>::new(), &USER_GROUPS, [user.id])
.await?
.remove(&user.id)
.unwrap_or_default();
Ok(Some(Identity {
id: user.id,
is_superuser: user.is_superuser,
is_staff: user.is_staff,
groups: groups.into_iter().map(|g| g.slug).collect(),
..Default::default()
}))
})
}
}
}
The application gives it to rind once, in
app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
// .models(…), .api(…)
.auth(accounts_ops::TokenAuth)
}
Now a request with Authorization: Bearer root-token is the sample’s
superuser, and a request without the header is anonymous:
GET /reservations
Authorization: Bearer root-token
{"nav": {…}, "results": [{"id": 1, …}, …]}
GET /reservations
{"detail": "Authentication credentials were not provided or are invalid."}
The second request gets a 401, because the rules of the reservations resource accept nobody anonymous (Permissions).
User and Group are ordinary models of the sample. rind asks nothing of
them: not their names, not their columns. The rest of this chapter
explains each part of the example.
This scheme is fine for a sample. A token that never expires, stored in clear in the database, is not what a real application wants. Use
rind-auth, or check a signed token as shown in Checking a signed token yourself.
The identity: what rind knows about a user
The answer to “who is asking?” is an Identity, or nobody (None):
#![allow(unused)]
fn main() {
// crates/rind-api/src/auth.rs
pub struct Identity {
pub id: i64,
pub is_superuser: bool,
pub is_staff: bool,
pub groups: Vec<String>, // the slugs of the user's groups
pub data: Option<Arc<dyn Any + Send + Sync>>,
}
}
It is much smaller than a Django User. It holds only what rind itself
reads, plus a slot for your own data:
idis the user’s key. Your own code reads it, for example to filter the reservations a user made (Reservation::made_by(user)). When the application has database replicas, rind also uses it to remember who just wrote, so that this user’s next read sees the write (Databases).is_staffandis_superuserare read by the rules#[rule(staff)]and#[rule(superuser)].groupsis read by the rule#[rule(group("…"))].datais never read by rind. It is for your application: see Carrying more than the flags.
These are rind’s words, not columns of a table. An application whose users
have no is_staff column decides what “staff” means for it when it
builds the identity, or it never uses that rule.
Identity implements Default, so you can write only the fields you set:
Identity { id: 1, is_staff: true, ..Default::default() }.
Coming from Django: there is no
request.userobject with a database row behind it. A resource that needs more than the identity loads the user itself, byid, or the authenticator attaches what is needed indata.
The three answers of an authenticator
An authenticator is a value that implements the Authenticate trait:
#![allow(unused)]
fn main() {
// crates/rind-api/src/auth.rs
pub trait Authenticate: Send + Sync + 'static {
fn authenticate<'a>(
&'a self,
db: &'a Db,
authorization: Option<&'a str>,
) -> BoxFuture<'a, Result<Option<Identity>, ApiError>>;
}
}
It receives the Authorization header of the request, exactly as the
client sent it (or None when there is none), and a database to look the
user up in. It gives one of three answers:
| Answer | Meaning | What happens to the request |
|---|---|---|
Ok(None) | no credentials, or a scheme this authenticator does not handle | it goes on as anonymous |
Ok(Some(identity)) | the credentials are this user’s | it goes on as that user |
Err(ApiError::Unauthorized) | there are credentials, but they are wrong | it is answered 401, even on a resource open to anyone |
This is the same contract as DRF’s authenticate(): return None to
pass, return a user, or raise AuthenticationFailed.
The last line is deliberate. A client that sends an expired token learns it at once, with a 401, instead of quietly reading the public data as nobody and wondering where its private data went.
Giving the authenticator to the application
The application gives its authenticator in app(), with .auth(..), as
in the first example. The authenticator is a value, built once when the
application starts. It can hold a key, a client of an identity provider,
or anything else that is costly to build.
Each request’s state, app.state(db), uses it. Code that builds an
AppState by hand gives the authenticator there instead:
#![allow(unused)]
fn main() {
let state = AppState::new(db, accounts_ops::TokenAuth);
}
The usual case: rind-auth
Most applications want their users to sign in with a name and a password,
and then send a signed token (a JWT) with each request. The
rind-auth crate does all of that: it mounts the login
routes, and it installs an authenticator that checks its own tokens. It
is added as a plugin, with .with(..):
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(
rind_auth::Auth::<accounts_models::User>::from_env()
.unwrap_or_else(|_| rind_auth::Auth::new("railway-development-secret"))
.groups(accounts_models::auth_groups()),
)
}
The plugin wraps the authenticator the application already had. A bearer
token that looks like a JWT is checked by rind-auth; any other header
goes to the previous authenticator. This is how the sample keeps its
simple Bearer root-token working beside real JWTs. Because the plugin
wraps what is there when it is installed, put .with(rind_auth::Auth…)
after .auth(..), not before.
The rest of this chapter is for applications that write their own authenticator.
Writing your own authenticator
Checking a signed token yourself
Sometimes something else signs the users in and hands out the token: an
identity provider, or another service. Each request then proves who it is
with that token. The authenticator checks the signature, then reads the
user. This fragment uses the jsonwebtoken crate:
#![allow(unused)]
fn main() {
pub struct JwtAuth {
key: DecodingKey,
validation: Validation,
}
// in `authenticate`:
let Some(token) = authorization.and_then(|h| h.strip_prefix("Bearer ")) else {
return Ok(None);
};
let claims = decode::<Claims>(token.trim(), &self.key, &self.validation)
.map_err(|_| ApiError::Unauthorized)?
.claims;
let user = db
.first(&Query::<User>::new().filter(User::id().eq(claims.user_id) & User::is_active().eq(true)))
.await?
.ok_or(ApiError::Unauthorized)?;
// … then build the Identity from `user`, as in the first example.
}
Reading the user at each request is a choice. It costs one query, and in exchange a user who was disabled a minute ago is refused now. An application that trusts its tokens for their whole lifetime can put the flags and the groups in the claims, and read no table at all.
If the tokens come from a Django service using simplejwt,
rind-auth can check them for you: see
Checking only.
Keys for other services, without a table of users
You do not need a table to have users. A service that is called by two other services can know each caller by a key, given in its settings:
#![allow(unused)]
fn main() {
pub struct Keys(pub HashMap<String, Identity>);
// in `authenticate`:
let Some(key) = authorization.and_then(|h| h.strip_prefix("Bearer ")) else {
return Ok(None);
};
self.0.get(key.trim()).cloned().map(Some).ok_or(ApiError::Unauthorized)
}
An unknown key is wrong credentials, so it gets a 401.
An application that signs nobody in
An application without .auth(..) (and without a plugin such as
rind-auth) signs nobody in. Every request is anonymous, as with the
authenticator rind::api::NoAuth. This is how rind new starts a
project.
In such an application, only #[rule(anyone)] ever accepts a request.
A resource with #[rule(staff)] or #[rule(authenticated)] answers
401 to everybody. It is closed, not broken. rind add resource warns
you when it writes a rule for the staff in an application that signs
nobody in.
Carrying more than the flags
What a user may see often depends on more than a flag: the stations they
manage, the companies they belong to. Reading that again in every
resource would cost a query each time. Instead, the authenticator reads it
once and attaches it to the identity with with_data:
#![allow(unused)]
fn main() {
pub struct Managed {
pub stations: Vec<i64>,
}
// at the end of `authenticate`:
Ok(Some(identity.with_data(Managed { stations })))
}
Any code that has the identity reads it back by its type, with
data::<T>():
#![allow(unused)]
fn main() {
pub fn managed_by(user: &Identity) -> Query<Station> {
let stations = user.data::<Managed>().map(|m| m.stations.clone()).unwrap_or_default();
Query::new().filter(Station::id().in_(stations))
}
}
data::<T>() returns None when the identity carries nothing of type
T. Put the type where both sides can name it: in a shared crate of the
users’ domain (Organising an application).
With rind-auth, the same thing is done with
.identity(..).
Where your code reads the identity
There are three places.
In the rules, without writing any code. The rules read the flags and the groups:
#![allow(unused)]
fn main() {
#[rule(superuser)]
#[rule(staff)]
#[rule(group("drivers"), actions(list, retrieve))]
#[rule(authenticated, actions(list, retrieve))]
}
In a mode’s query, where the identity is called user:
#![allow(unused)]
fn main() {
#[mode(ReservationMode::Own, query = Reservation::made_by(user), hide(booked_by))]
}
There is no Option to unwrap here. When the request is anonymous, a
query that names user matches no row.
In a hook, an action or a computed field, as ctx.user, which is an
Option<Identity>:
#![allow(unused)]
fn main() {
let user = ctx.user.as_ref().ok_or(ApiError::Unauthorized)?;
}
What a client is answered
Authentication and permissions together decide the status code:
| The request… | on a resource whose rules… | is answered |
|---|---|---|
| has wrong credentials | (anything) | 401 |
| has no credentials | accept nobody anonymous for this action | 401 |
| is a user’s | accept nobody of this kind for this action | 403 |
| is a user’s | accept, but in a mode whose query does not contain the object | 404 |
The Permissions chapter explains the last two lines.
Signing in, signing out, and passwords
The rind-auth crate gives all of these. An application
that does not use it writes them as ordinary code; rind has nothing to add:
- A login route takes a name and a password, checks them, and answers
a token. It is not a resource. It is a plain route of the web framework,
merged with rind’s router (or added to the same actix
App), that calls an operation of the users’ domain (Routes that are not resources). - Passwords are hashed with a crate made for it (
argon2, for example). An application that takes over a Django database must read Django’s format (pbkdf2_sha256$…) with the same care;rind-authdoes. - Signing out is the client forgetting its token, or the application keeping a list of revoked tokens that its authenticator reads.
- “Who am I?” is a route that answers the user of the request. Outside
any resource, with an
AppState, the user isstate.ctx(authorization).await?.user.
In the tests
A test that calls the pipeline without HTTP builds its context with the user it wants:
#![allow(unused)]
fn main() {
let staff = Identity { id: 1, is_staff: true, ..Default::default() };
let ctx = Ctx::new(db.clone(), Some(staff));
}
A scope is tested as the plain function it is: Reservation::made_by(&user)
is a query, which you run on the test database. Through HTTP, the sample’s
tests send the tokens of its seed data (sample/tests/common/api_cases.rs).
Reference
Limits
These are stated plainly, so that nobody looks for them:
- Only the
Authorizationheader reaches the authenticator. Not the cookies, not another header, not the client’s address. A session in a cookie, or a key inX-Api-Key, needs a layer of the web framework in front of rind that rewrites it as anAuthorizationheader. - The authenticator runs at every request, and rind keeps nothing between two requests. An application that wants a cache of users puts it in its authenticator.
- An identity’s
idis ani64. Users known by a UUID need a number beside it. - OpenAPI always says
bearer. The OpenAPI document declares one security scheme, an HTTP bearer token, whatever your authenticator really reads. Operations open to anyone have no security requirement.
Types
| Name | Where | What it is |
|---|---|---|
Identity | rind::api | who is asking: id, is_staff, is_superuser, groups, data |
Identity::with_data(value) | attaches application data, read back with data::<T>() | |
Authenticate | rind::api | the trait an authenticator implements |
NoAuth | rind::api | an authenticator for which every request is anonymous |
Application::auth(value) | rind | gives the application’s authenticator |
AppState::new(db, auth) | rind::api | a state built by hand, with its authenticator |
AppState::ctx(authorization) | the context (and so the user) of an Authorization header | |
Ctx::new(db, user) | rind::api | a context for a test, a command or a job |