---
title: Authentication and Authorisation
description: Signing users up, in and out with the authentication generator, protecting routes, checking permissions, throttling sign-in attempts, and working with an existing Rails app's passwords and tokens.
category: Going Further
order: 2
---
Glacier doesn't hide authentication inside the framework. A generator
writes sign up, sign in and sign out into your app as ordinary code, with
its tests, and the framework supplies only the parts that are easy to get
wrong: password hashing and session tokens.
After reading this guide, you will know:
- What `glacier generate authentication` writes, and how it works.
- How passwords and session tokens are stored.
- How to let only signed-in users reach a route.
- How to check what a signed-in user may do, with policies, and how to
catch actions that don't check.
- How to limit sign-in attempts.
- How to authenticate an API with bearer tokens.
- How an existing Rails app's bcrypt passwords and JSON Web Tokens carry
over.
The examples come from two apps. `accounts` is an HTML app with notes
that belong to the user who wrote them; `api` is a JSON API, described in
[Building JSON APIs](json_apis.html).
## Generating Authentication
In a new app, run the generator:
```sh
$ glacier generate authentication
create src/migrations/m20261004100420_create_users.rs
update src/migrations/mod.rs
create src/migrations/m20261004100421_create_sessions.rs
update src/migrations/mod.rs
create src/models/user.glacier
create src/models/session.glacier
update src/models/mod.rs
update src/models/mod.rs
create src/authentication.rs
create src/controllers/sessions_controller.glacier
create src/controllers/registrations_controller.glacier
update src/controllers/mod.rs
update src/controllers/mod.rs
create src/views/sessions/new.html
create src/views/registrations/new.html
create tests/factories/user.glacier
create tests/models/user.test.glacier
create tests/controllers/sessions_controller.test.glacier
create tests/controllers/registrations_controller.test.glacier
update tests/glacier.rs
update src/lib.rs
update src/routes.rs
Next: glacier db migrate. Routes for signed-in users go in a scope
through the `authenticated` pipeline:
scope "/" through browser, authenticated {
get "/account" => Accounts::show, as account;
}
and `current_user(&ctx)` (alias Authentication.current_user) is who's signed in.
```
That's:
- `User` and `Session` models, and migrations for their tables.
- `src/authentication.rs`, which finds who is signed in on each request,
and the middleware that keeps signed-out visitors away from a route.
- A sessions controller (sign in and out) and a registrations controller
(sign up), with their pages.
- Tests for all of it, and a `User` factory, which gives each user it
makes an email address of their own (see
[Testing](testing.html#sequences)).
It also registers the middleware in `src/lib.rs` and adds the routes. The
generator won't run in an app that already has a `User` or `Session`
model, `src/authentication.rs`, or either controller.
After `glacier db migrate`, `/registration/new` signs up and
`/session/new` signs in. The rest of this chapter walks through what was
written.
### Users
```glacier
model User do
field email_address: String, required, unique
field password_digest: String, protected
# Set from a form or JSON, and stored only as password_digest.
field password: Option<String>, virtual
has_many :sessions
# The user with this email address and password, if any. It takes as
# long either way, so it doesn't reveal who has an account.
def authenticate_by(email_address: &str, password: &str) -> Option<User> do
user = User.find_by(email_address: User.normalize_email(email_address))!
digest = user.as_ref().map(fn u -> u.password_digest.as_str() end)
if glacier::auth::verify_password(password, digest) do
user
else
None
end
end
def normalize_email(email_address: &str) -> String do
email_address.trim().to_lowercase()
end
validate do
if self.password_digest.is_empty() and self.password.is_none() do
errors.add("password", "can't be blank")
end
if self.password.as_ref().is_some_and(fn p -> p.chars().count() < 8 end) do
errors.add("password", "is too short (minimum is 8 characters)")
end
end
before_validation do
self.email_address = User.normalize_email(&self.email_address)
end
before_save do
if self.password.is_some() do
self.password_digest = glacier::auth::hash_password(&self.password.take().unwrap_or_default())
end
end
end
```
`password` is a `virtual` field: it's set from the sign-up form but never
stored. `before_save` replaces it with its hash in `password_digest`. The
`validate` block requires a password for a new user and checks its
length. Email addresses are trimmed and lower-cased before validation, so
`" USER@example.com "` and `user@example.com` are the same account.
`password_digest` is `protected`, so it can't be set from params: a form
that sends `password_digest` is ignored, and only `password` changes it:
```glacier
test "ignores a password_digest sent as a param" do
user = User.build([email_address: "new@example.com", password_digest: "not a hash"])
refute user.save()!
assert user.password_digest == ""
assert user.errors_on("password") == ["can't be blank"]
end
```
`authenticate_by` finds the user and checks the password. When there's no
user with that email address, `glacier::auth::verify_password` still
spends the time of an Argon2 check, so for accounts with Argon2 passwords,
signing in takes about as long whether or not the email address has an
account. (Passwords imported from a Rails app are a different case; see
[Existing Rails Apps](#existing-rails-apps).)
### Sessions
Each sign-in is a row in `sessions`:
```glacier
model Session do
field token_digest: String, required, unique, protected
field user_agent: Option<String>
belongs_to :user
# Starts a session for the user, returning its token for the client. The
# database keeps only the token's digest.
def start(user_id: i64, user_agent: Option<String>) -> String do
token = glacier::auth::new_token()
session = Session.new(user_id: user_id, user_agent: user_agent, token_digest: glacier::auth::token_digest(&token))
session.save()!
token
end
# The session with this token, and its user.
def find_by_token(token: &str) -> Option<Session> do
Session.where(token_digest: glacier::auth::token_digest(token)).preload(:user).first()!
end
end
```
```rust
use glacier::db::migration::*;
pub fn up(s: &mut Schema) {
s.create_table("sessions", |t| {
t.references("user").not_null().on_delete_cascade();
// Only the token's digest: the token itself stays with the client.
t.string("token_digest").not_null().unique();
t.string("user_agent");
t.timestamps();
});
}
pub fn down(s: &mut Schema) {
s.drop_table("sessions");
}
```
`Session.start` makes a new token for the client and stores only its
digest. `Session.find_by_token` digests the token a request sends and
looks that up, loading the user with it.
### Passwords and Tokens
The generated code relies on five functions in `glacier::auth`:
| `hash_password(password)` | An Argon2id hash with a random 16-byte salt and the `argon2` crate's default cost (`m=19456,t=2,p=1`), as a PHC string (`$argon2id$v=19$m=19456,t=2,p=1$…`) |
| `verify_password(password, digest)` | Whether the password matches the digest; `digest` is an `Option`, and `None` still takes the time of a check |
| `new_token()` | 32 random bytes from the operating system, base64url-encoded (43 characters) |
| `token_digest(token)` | The token's SHA-256 digest, hex-encoded |
| `bearer_token(&ctx)` | The token from an `Authorization: Bearer …` header, if the request has one |
Only the digest of a session token is stored, so someone who reads the
`sessions` table can't use what they find there to sign in. The token
itself goes to the browser, inside the session cookie.
The generated `User` tests check the password half of this:
```glacier
test "stores only a hash of the password" do
user = insert(User, email_address: "user@example.com")
assert user.password_digest.starts_with("$argon2id$")
assert user.password.is_none()
end
test "signs in with the right password only" do
insert(User, email_address: "user@example.com")
assert User.authenticate_by("user@example.com", "password")!.is_some()
assert User.authenticate_by(" USER@example.com ", "password")!.is_some()
assert User.authenticate_by("user@example.com", "wrong")!.is_none()
assert User.authenticate_by("nobody@example.com", "password")!.is_none()
end
test "needs a password of 8 characters or more" do
user = User.build(params_for(User, password: "short"))
refute user.save()!
assert user.errors_on("password") == ["is too short (minimum is 8 characters)"]
end
test "email addresses are unique, whatever their case" do
insert(User, email_address: "user@example.com")
user = User.build(params_for(User, email_address: "User@Example.com"))
refute user.save()!
assert user.errors_on("email_address") == ["has already been taken"]
end
```
### Signing Up, In and Out
The controllers are short, because the work is in the models and
`src/authentication.rs`:
```glacier
alias Authentication.start_session
controller Registrations do
def new do
render user: User.new(), title: "Sign up"
end
def create(ctx) do
user = User.build(ctx.params())
if user.save()! do
start_session(&ctx, &user)!
redirect "/", notice: "Welcome!"
else
render :new, user, title: "Sign up", status: 422
end
end
end
```
```glacier
alias Authentication.start_session
alias Authentication.end_session
alias Authentication.after_sign_in_path
controller Sessions do
def new do
render email_address: "", alert: "", title: "Sign in"
end
def create(ctx) do
params = ctx.params()
email_address = params.get("email_address").unwrap_or_default()
password = params.get("password").unwrap_or_default()
case User.authenticate_by(email_address, password)! do
Some(user) ->
start_session(&ctx, &user)!
redirect after_sign_in_path(&ctx), notice: "Signed in."
None ->
alert = "Try another email address or password."
render :new, email_address: email_address, alert: alert, title: "Sign in", status: 422
end
end
def destroy(ctx) do
end_session(&ctx)!
redirect new_session_path(), notice: "Signed out."
end
end
```
A wrong email address and a wrong password get the same message, so the
sign-in page doesn't reveal which accounts exist. The sign-up page does: an
email address that's already registered gets "has already been taken". The routes go through the
`browser` pipeline, so the forms are protected against CSRF:
```rust
scope "/" through browser {
get "/session/new" => Sessions::new, as new_session;
post "/session" => Sessions::create, as session;
delete "/session" => Sessions::destroy;
get "/registration/new" => Registrations::new, as new_registration;
post "/registration" => Registrations::create, as registration;
}
```
## Who's Signed In
`src/authentication.rs` is the core of it. The `Authentication`
middleware runs on every request: it reads a token from an
`Authorization: Bearer` header or, failing that, from the session cookie,
and if a session has that token, it stores the session and its user in
the request:
```rust
/// Finds each request's session, from the session cookie or a bearer token.
/// Register it on the app, so every page knows who's signed in.
pub struct Authentication;
impl Middleware for Authentication {
fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
Box::pin(async move {
let token = match glacier::auth::bearer_token(&ctx) {
Some(token) => Some(token.to_owned()),
None => ctx.session().get::<String>(SESSION_TOKEN),
};
if let Some(token) = token
&& let Ok(Some(session)) = Session::find_by_token(&token).await
&& let Some(user) = session.user.get().cloned()
{
ctx.extensions_mut().insert(Current { user, session });
}
next.run(ctx).await
})
}
}
```
The generator registers it on the app in `src/lib.rs`:
```rust
// Who's signed in, for every request.
.middleware(authentication::Authentication)
```
`current_user(&ctx)` gives the signed-in user, if there is one:
```rust
/// The signed-in user and their session, found by [`Authentication`].
#[derive(Clone)]
pub struct Current {
pub user: User,
pub session: Session,
}
/// The signed-in user, if there is one.
pub fn current_user(ctx: &Context) -> Option<&User> {
ctx.extensions().get::<Current>().map(|current| ¤t.user)
}
```
Signing in and out happens in two functions the controllers call:
```rust
/// Signs `user` in: a new session, with its token in the browser's session
/// cookie. Returns the token too, for API clients.
pub async fn start_session(ctx: &Context, user: &User) -> glacier::Result<String> {
let user_agent = ctx.header("user-agent").map(str::to_owned);
let token = Session::start(user.id, user_agent).await?;
ctx.session().insert(SESSION_TOKEN, &token)?;
Ok(token)
}
/// Signs out: ends the current session, however its token was sent.
pub async fn end_session(ctx: &Context) -> glacier::Result<()> {
if let Some(current) = ctx.extensions().get::<Current>() {
current.session.clone().destroy().await?;
}
ctx.session().remove(SESSION_TOKEN);
Ok(())
}
```
The browser's session cookie is encrypted, `HttpOnly`, `SameSite=Lax`,
and `Secure` in production. It has no expiry date, so the browser usually
drops it when it closes, but the row in `sessions` stays until the user signs
out.
WARNING: Sessions don't expire. The generated code has no time limit on a
session token, so a token stays valid until its session row is deleted,
which only signing out (or deleting the user) does. Signing out ends only
the current session, and changing the password leaves the user's other
sessions valid. If your app needs sessions to expire, check
the session's `inserted_at` in `Session.find_by_token`.
## Protecting Routes
The generator adds an `authenticated` pipeline to `src/routes.rs`:
```rust
// Only for signed-in users; see src/authentication.rs.
pipeline authenticated = Pipeline::new().with(RequireAuthentication);
```
and routes that only signed-in users may reach go in a scope through it,
after `browser`:
```rust
scope "/" through browser, authenticated, authorized {
resources "/notes" => Notes;
get "/account" => Accounts::show, as account;
}
```
(The `authorized` pipeline is covered in
[Authorisation](#catching-a-missing-authorize).)
`RequireAuthentication` lets a signed-in request through. Anyone else is
sent to sign in, or, if the request looks like an API client's (it has a
bearer token, or its `Accept` header asks for JSON), answered with
`401 Unauthorized`:
```rust
/// Lets only signed-in users through. A browser is sent to sign in, and
/// back here afterwards; an API client gets `401 Unauthorized`.
pub struct RequireAuthentication;
impl Middleware for RequireAuthentication {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
Box::pin(async move {
if ctx.extensions().get::<Current>().is_some() {
return next.run(ctx).await;
}
let api = glacier::auth::bearer_token(&ctx).is_some()
|| ctx
.header("accept")
.is_some_and(|accept| accept.contains("application/json"));
if api {
return Error::new(StatusCode::UNAUTHORIZED, "sign in first").into_response();
}
if *ctx.method() == Method::GET {
let _ = ctx.session().insert(RETURN_TO, ctx.uri().to_string());
}
Response::redirect(&crate::routes::new_session_path())
})
}
}
```
For a `GET`, it remembers the page in the session, and after signing in,
`after_sign_in_path` sends the browser back there:
```rust
/// Where to go after signing in: the page that sent the browser to sign in,
/// or the home page.
pub fn after_sign_in_path(ctx: &Context) -> String {
let path = ctx.session().get::<String>(RETURN_TO);
ctx.session().remove(RETURN_TO);
path.unwrap_or_else(|| "/".to_owned())
}
```
The notes tests check the whole round trip:
```glacier
test "sends a signed-out visitor to sign in, and back afterwards" do
res = get "/notes"
assert res.status == :see_other
assert res.location == "/session/new"
user = insert(User)
get res.location
res = post "/session", [email_address: &user.email_address, password: "password"]
assert res.location == "/notes"
end
```
### The Signed-In User in an Action
Inside the `authenticated` scope, `current_user(&ctx)` is always `Some`.
The `accounts` app adds a small function to `src/authentication.rs` that
turns it into a `Result`, so an action can use `?`:
```rust
/// The signed-in user, for actions behind the `authenticated` pipeline,
/// which has already sent everyone else to sign in.
pub fn signed_in_user(ctx: &Context) -> glacier::Result<&User> {
current_user(ctx).ok_or_else(|| Error::new(StatusCode::UNAUTHORIZED, "sign in first"))
}
```
`create` uses it to give a new note its owner. The `user_id` is set after
`Note.build(ctx.params())`, so a `user_id` sent with the form can't make
the note someone else's:
```glacier
def create(ctx) do
user = signed_in_user(&ctx)?
authorize NotePolicy.create(user)
note = Note.build(ctx.params())
# Whoever is signed in, never a user_id sent with the form.
note.user_id = user.id
if note.save()! do
redirect note, notice: "Note created."
else
render :new, note, title: "New note", status: 422
end
end
```
```glacier
test "creates a note for the signed-in user" do
user = sign_in()
other = insert(User)
res = post "/notes", params_for(Note, user_id: other.id)
assert res.status == :see_other
assert get(res.location).body =~ "Note created."
assert Note.first()!.unwrap().user_id == user.id
end
```
`update` needs the same care. `note.update(ctx.params())` would accept a
`user_id` from the form, so a user could hand their note to someone else.
Glacier can't mark a `belongs_to` key `protected` yet, so the action
leaves `user_id` out of the params with `without` before updating:
```glacier
def update(ctx) do
note = Note.find(ctx.id()?)!
authorize NotePolicy.update(signed_in_user(&ctx)?, ¬e)
# A note keeps its owner, whatever user_id the form sends.
if note.update(ctx.params().without("user_id"))! do
redirect note, notice: "Note updated."
else
render :edit, note, title: "Edit note", status: 422
end
end
```
```glacier
test "keeps a note's owner when the form sends another user_id" do
user = sign_in()
other = insert(User)
note = insert(Note, user_id: user.id)
res = patch note, params_for(Note, user_id: other.id), title: "Mine"
assert res.status == :see_other
assert Note.find(note.id)!.user_id == user.id
end
```
## Authorisation
Signing in says who someone is; authorisation says what they may do.
The rules are your app's own code, and `authorize` checks them in an
action.
### Policies
By convention, the rules for a model go in a policy, one per model. The
generator writes one, once the app has a `User` model (it refuses to run
without `src/models/user.glacier` or `user.rs`, which `glacier generate
authentication` writes):
```sh
$ glacier generate policy Note
create src/services/note_policy.glacier
create src/services/mod.rs
update src/lib.rs
Next: decide each rule in src/services/note_policy.glacier, then `authorize NotePolicy.show(user, note)`
in the actions. Add `VerifyAuthorized` to a pipeline to catch actions that forget.
```
A policy is a `service` (see [The .glacier
Language](glacier_language.html)) with a rule for each of `index`,
`show`, `create`, `update` and `destroy` (`new` and `edit` use `create` and
`update`). Each takes the user, and the
rules for one record take the record too. The generator writes every rule
as `false`, so nothing is allowed until you decide, with its arguments
named `_user` and `_note` so that the stubs build without warnings. In
the `accounts` app, any signed-in user may list and write notes, and only
a note's own user may see, change or delete it:
```glacier
# Who may do what with notes: any signed-in user may list and write
# notes, and only a note's own user may see, change or delete it.
service NotePolicy do
# Whether the user may list them.
def index(_user: &User) -> bool do
true
end
# Whether the user may see one.
def show(user: &User, note: &Note) -> bool do
note.user_id == user.id
end
# Whether the user may make one.
def create(_user: &User) -> bool do
true
end
# Whether the user may change this one.
def update(user: &User, note: &Note) -> bool do
note.user_id == user.id
end
# Whether the user may delete this one.
def destroy(user: &User, note: &Note) -> bool do
note.user_id == user.id
end
end
```
A rule is an ordinary function, so a test can call it directly:
```glacier
test "lets only a note's own user change it" do
user = insert(User)
other = insert(User)
note = insert(Note, user_id: user.id)
assert NotePolicy.update(&user, ¬e)
refute NotePolicy.update(&other, ¬e)
refute NotePolicy.destroy(&other, ¬e)
end
```
### Checking With `authorize`
`authorize` in an action answers `403 Forbidden` unless the rule allows
it. A controller brings the policy in with `alias Services.NotePolicy`:
```glacier
controller Notes do
def index(ctx) do
user = signed_in_user(&ctx)?
authorize NotePolicy.index(user)
notes = Note.where(user_id: user.id).order(inserted_at: :desc)!
render notes, title: "Notes"
end
def show(ctx) do
note = Note.find(ctx.id()?)!
authorize NotePolicy.show(signed_in_user(&ctx)?, ¬e)
render note, title: "Note"
end
```
`authorize` takes any `bool` expression, so a policy is a convention
rather than a requirement: a method on the model, or a check written in
place, works the same way. It compiles to a call to `glacier::authorize`,
which returns an error with status 403 when the expression is false, and
`?` returns it from the action. In a controller written in Rust, call
`glacier::authorize(allowed)?` yourself.
Lists need their own filter, as `index` does with
`where(user_id: user.id)`, because `authorize` checks one thing at a time:
`NotePolicy.index(user)` says whether the user may list notes at all, not
which notes they see.
```glacier
describe "someone else's note" do
setup do
sign_in()
end
test "can't be seen" do
other = insert(User)
note = insert(Note, user_id: other.id)
assert get(note).status == :forbidden
end
test "can't be deleted" do
other = insert(User)
note = insert(Note, user_id: other.id)
assert delete(note).status == 403
assert Note.count()! == 1
end
end
```
### Catching a Missing `authorize`
An action that never calls `authorize` is open to every user who can reach
it. `glacier::middleware::VerifyAuthorized` catches that: on a pipeline,
it checks each request's action once it has answered. The `accounts` app
adds a pipeline for it to the notes routes:
```rust
// Every action here must `authorize` (or `skip_authorization`).
pipeline authorized = Pipeline::new().with(VerifyAuthorized);
```
```rust
scope "/" through browser, authenticated, authorized {
resources "/notes" => Notes;
get "/account" => Accounts::show, as account;
}
```
When the action answers with a status below 400 and neither `authorize`
nor `skip_authorization` was called while handling the request,
`VerifyAuthorized` logs an error naming the method and path. Outside
production it also replaces the response with `500 Internal Server
Error`; in production the response goes out unchanged. Which one applies
is set by the `GLACIER_ENV` variable, and an app without it counts as
development, so a production server must set `GLACIER_ENV=production`. An error response
(`4xx` or `5xx`) passes through, so a note that isn't found is still a
`404`. Routes outside the pipeline aren't checked.
Removing the `authorize` line from `destroy` makes both `destroy` tests
fail; this is the one for someone else's note:
```text
---- controllers::notes_controller::someone_else_s_note::can_t_be_deleted stdout ----
thread '<unnamed>' (12897264) panicked at tests/controllers/notes_controller.test.glacier:135:5:
assertion failed: delete(note).status == 403
left: :internal_server_error (500)
right: 403
```
WARNING: `VerifyAuthorized` finds a missing `authorize` in development
and in tests; it doesn't protect anything in production. It checks only
after the action has run, so whatever the action did, such as deleting
someone else's note here, has already happened by the time the response
is replaced, and in production the response isn't replaced at all. It
checks only that `authorize` was called, allowed or not, not that the
rule or the record was the right one, and it doesn't check that a list is
filtered. It's a net for tests that request every action, not a
replacement for `authorize`.
`skip_authorization`, on a line of its own in an action
(`glacier::skip_authorization()` in Rust), marks an action as having
nothing to authorize. Every signed-in user may see their own account
page, so the `accounts` app's `Accounts.show` skips:
```glacier
controller Accounts do
# Every signed-in user may see their own account, so there's nothing to
# authorize.
def show(ctx) do
skip_authorization
email_address = signed_in_user(&ctx)?.email_address.clone()
render email_address: email_address, title: "Account"
end
end
```
```glacier
test "shows the signed-in user their account" do
user = insert(User)
get "/session/new"
post "/session", [email_address: &user.email_address, password: "password"]
res = get "/account"
assert res.status == :ok
assert res.body =~ format!("Signed in as {}.", user.email_address)
end
```
Pipelines run in the order a scope lists them, so `authorized` comes after
`authenticated`. The other way round, the redirect that sends a
signed-out visitor to sign in is checked too: it isn't an error response
and no action authorized it, so outside production it becomes a `500`,
and in production each one logs an error.
## Throttling Sign-In Attempts
`glacier::middleware::Throttle` limits how often something can happen. It
takes a name
(for the log), a limit, a period, and a function that picks the key to
count a request under, or `None` to leave the request alone. The
`accounts` app counts sign-in attempts per email address:
```rust
// At most 5 sign-in attempts a minute for each email address.
.middleware(Throttle::new("sign-in", 5, Duration::from_secs(60), |ctx| {
let signing_in = *ctx.method() == Method::POST && ctx.path() == "/session";
let email = ctx.params().get("email_address")?.trim().to_lowercase();
signing_in.then_some(email)
}))
```
Over the limit, the answer is `429 Too Many Requests` with the body
`Retry later`, until the period's window ends:
```glacier
test "allows 5 sign-in attempts a minute for each email address" do
insert(User, email_address: "user@example.com")
for _ in 0..5 do
res = post "/session", [email_address: "user@example.com", password: "wrong"]
assert res.status == :unprocessable_entity
end
res = post "/session", [email_address: "user@example.com", password: "password"]
assert res.status == :too_many_requests
res = post "/session", [email_address: "other@example.com", password: "password"]
assert res.status == :unprocessable_entity
end
```
Some details to know:
- Requests are counted in fixed windows of the period (each minute, here),
not a sliding one, so up to twice the limit can get through around the
boundary between two windows.
- Counts are kept in memory, in each process. Several processes or
servers each count separately, and a restart starts afresh.
- The period must be at least a second, and is counted in whole seconds.
- Registered on the app with `.middleware(…)`, as here, a throttle runs
before routing, for every request. It can go in a pipeline instead,
with `Pipeline::new().with(Throttle::new(…))`, to cover only that
pipeline's routes.
### Client IP Addresses
To throttle by client instead, use `ctx.remote_ip()`. It's the address of the connection, unless that
is a trusted proxy, in which case it's the nearest address in the
`X-Forwarded-For` header that isn't one (or the first address in it, if
they all are; or the connection's address, if the header is missing). Trusted proxies are loopback and
private network addresses (`127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`,
`192.168.0.0/16`, `::1` and `fc00::/7`); the list can't be configured yet.
`remote_ip()` returns `None` when there's no connection, which is the case
in tests, so a throttle keyed on it counts nothing in tests.
## Authenticating an API
`glacier generate authentication --api` writes the same models, with
controllers that speak JSON and clients that send their token in an
`Authorization: Bearer` header instead of a cookie. In an app made with
`glacier new --api`, which has no pages, plain `glacier generate
authentication` writes this flavour too; `--api` is for an app that also
has pages, as the `api` app does:
```sh
$ glacier generate authentication --api
create src/migrations/m20261004100423_create_users.rs
update src/migrations/mod.rs
create src/migrations/m20261004100424_create_sessions.rs
update src/migrations/mod.rs
create src/models/user.glacier
create src/models/session.glacier
update src/models/mod.rs
update src/models/mod.rs
create src/authentication.rs
create src/controllers/sessions_controller.glacier
create src/controllers/registrations_controller.glacier
update src/controllers/mod.rs
update src/controllers/mod.rs
create tests/factories/user.glacier
create tests/models/user.test.glacier
create tests/controllers/sessions_controller.test.glacier
create tests/controllers/registrations_controller.test.glacier
update tests/glacier.rs
update src/lib.rs
update src/routes.rs
Next: glacier db migrate. Routes for signed-in users go in a scope
through the `authenticated` pipeline:
scope "/" through api, authenticated {
get "/account" => Accounts::show, as account;
}
and `current_user(&ctx)` (alias Authentication.current_user) is who's signed in.
```
The `User` and `Session` models are the same. Signing in returns the
token, with `201 Created`; signing out answers `204 No Content`:
```glacier
alias Authentication.start_session
alias Authentication.end_session
controller Sessions do
# Signs in, returning the token to send as `Authorization: Bearer <token>`.
def create(ctx) do
params = ctx.params()
email_address = params.get("email_address").unwrap_or_default()
password = params.get("password").unwrap_or_default()
case User.authenticate_by(email_address, password)! do
Some(user) ->
token = start_session(&ctx, &user)!
json [token: token], status: :created
None ->
json [error: "Try another email address or password."], status: :unauthorized
end
end
def destroy(ctx) do
end_session(&ctx)!
head :no_content
end
end
```
```glacier
alias Authentication.start_session
controller Registrations do
# Signs up and signs in, returning the token as `Sessions` does.
def create(ctx) do
user = User.build(ctx.params())
if user.save()! do
token = start_session(&ctx, &user)!
json [token: token], status: :created
else
json user.errors_json(), status: :unprocessable_entity
end
end
end
```
`src/authentication.rs` reads only the bearer token, and
`RequireAuthentication` always answers `401 Unauthorized`:
```rust
//! Signing in and out, and who's signed in. Written by `glacier generate
//! authentication`; it's your code now, so change it as you need.
//!
//! A session is a row in `sessions`. The client gets its token when it
//! signs in and sends it as `Authorization: Bearer <token>`. The database
//! stores only the token's SHA-256 digest.
use glacier::handler::BoxFuture;
use glacier::prelude::*;
use crate::models::{Session, User};
/// The signed-in user and their session, found by [`Authentication`].
#[derive(Clone)]
pub struct Current {
pub user: User,
pub session: Session,
}
/// The signed-in user, if there is one.
pub fn current_user(ctx: &Context) -> Option<&User> {
ctx.extensions().get::<Current>().map(|current| ¤t.user)
}
/// Finds each request's session from its bearer token. Register it on the
/// app, so every request knows who's signed in.
pub struct Authentication;
impl Middleware for Authentication {
fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
Box::pin(async move {
let token = glacier::auth::bearer_token(&ctx).map(str::to_owned);
if let Some(token) = token
&& let Ok(Some(session)) = Session::find_by_token(&token).await
&& let Some(user) = session.user.get().cloned()
{
ctx.extensions_mut().insert(Current { user, session });
}
next.run(ctx).await
})
}
}
/// Lets only signed-in users through; others get `401 Unauthorized`.
pub struct RequireAuthentication;
impl Middleware for RequireAuthentication {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
Box::pin(async move {
if ctx.extensions().get::<Current>().is_some() {
return next.run(ctx).await;
}
Error::new(StatusCode::UNAUTHORIZED, "sign in first").into_response()
})
}
}
/// Signs `user` in: a new session, whose token the client sends from now on.
pub async fn start_session(ctx: &Context, user: &User) -> glacier::Result<String> {
let user_agent = ctx.header("user-agent").map(str::to_owned);
Session::start(user.id, user_agent).await
}
/// Signs out: ends the current session.
pub async fn end_session(ctx: &Context) -> glacier::Result<()> {
if let Some(current) = ctx.extensions().get::<Current>() {
current.session.clone().destroy().await?;
}
Ok(())
}
```
The routes go through an `api` pipeline, which the generator adds if the
app doesn't have one: it renders errors as JSON and has no CSRF check,
because API clients send a token rather than a cookie.
In tests, `glacier::testing::bearer(token)` sends the token with every
later request, as a client that has signed in would:
```glacier
test "signs in, returning a token" do
insert(User, email_address: "user@example.com")
res = post "/session", [email_address: "user@example.com", password: "password"]
assert res.status == :created
assert res.body =~ "\"token\":"
assert Session.count()! == 1
end
test "rejects a wrong password" do
insert(User, email_address: "user@example.com")
res = post "/session", [email_address: "user@example.com", password: "wrong"]
assert res.status == :unauthorized
assert Session.count()! == 0
end
test "signs out the session whose token is sent" do
user = insert(User, email_address: "user@example.com")
token = Session.start(user.id, None)!
glacier::testing::bearer(&token)
res = delete "/session"
assert res.status == :no_content
assert Session.count()! == 0
end
```
A page on another origin that calls the API from a browser needs the API
to allow that origin, with `glacier::middleware::Cors` (see
[Cross-Origin Requests](json_apis.html#cross-origin-requests)). A bearer
token isn't a cookie, so the browser sends it only when the page's script
adds it, and the API doesn't need CORS credentials for it.
## Existing Rails Apps
### Devise and `has_secure_password` Passwords
Devise and `has_secure_password` store bcrypt hashes (`$2a$…`).
`glacier::auth::verify_password` recognises them and checks them as
bcrypt, so the generated `User.authenticate_by` signs in users whose
passwords a Rails app hashed, without changes. New and changed passwords
are hashed with Argon2id. The hash in this test was made by Ruby's
`bcrypt` gem:
```glacier
test "signs in a user whose password Devise hashed with bcrypt" do
# Ruby's BCrypt::Password.create("secret", cost: 4), as Devise and
# has_secure_password store it.
digest = "$2a$04$KJY25RprEuJvbxVtp0EL6OAwC3ZAHpva.goKBL6bcCq6/HLxIEkUu"
user = User.new(email_address: "devise@example.com", password_digest: digest)
assert user.save()!
assert User.authenticate_by("devise@example.com", "secret")!.is_some()
assert User.authenticate_by("devise@example.com", "wrong")!.is_none()
end
```
WARNING: Checking a bcrypt hash takes as long as its cost makes it, and
Devise's default cost of 12 is much slower than Glacier's Argon2 check. So
while users still have bcrypt hashes, response times can show which email
addresses belong to them. A bcrypt hash isn't replaced with an Argon2 one
when its user signs in; it changes only when the password does.
To use an existing `users` table, the `User` model's fields must match
its columns: Devise's column is `encrypted_password` and its email column
is `email`, where the generator uses `password_digest` and
`email_address`.
### JSON Web Tokens
`glacier::auth::jwt` signs and checks JSON Web Tokens signed with
HMAC-SHA256 (`HS256`), as Rails apps using Ruby's `jwt` gem issue them,
so a Glacier app can accept tokens a Rails app issued, and the other way
round:
- `jwt::encode(&claims, secret)` returns a token for the claims (a JSON
object), with the header `{"alg":"HS256"}` and the claims' keys in
order. The token in this test is byte for byte the one Ruby's `jwt` gem
makes for the same claims and secret.
- `jwt::decode(token, secret)` checks the signature, in constant time, and
the `exp` claim if there is one, and returns the claims. `exp` must be a
whole number of seconds (anything else is malformed), and a token is
expired from that second on, with no allowance for clock skew.
```glacier
test "reads a token signed by the Rails app's jwt gem" do
# Ruby: JWT.encode({user_id: 1, email: "a@b.c", exp: 4102444800}, "s", "HS256")
token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6ImFAYi5jIiwiZXhwIjo0MTAyNDQ0ODAwfQ.6DVTKEZh7vTr7ohSSxZEV8iyMg6REQCYy7-nCjR3oVk"
claims = glacier::auth::jwt::decode(token, b"s").unwrap()
assert claims["user_id"] == 1
assert claims["email"] == "a@b.c"
assert glacier::auth::jwt::encode(&claims, b"s") == token
assert glacier::auth::jwt::decode(token, b"another secret").is_err()
end
```
`decode` fails with a `JwtError`: `Malformed`, `Algorithm` (the header
isn't `HS256`), `Signature` or `Expired`. It checks nothing else: not
`nbf`, `iat`, `iss` or `aud`, so check any of those your app relies on in
the claims it returns. Other algorithms, such as RS256, aren't supported.
## What Isn't Built Yet
Many apps need more than the generator writes. Glacier doesn't have
these yet:
- Password resets and email confirmation (they need mailers, which
Glacier doesn't have yet), magic links and "remember me".
- Expiring sessions (see the warning above).
- A check that an action filtered a list to what the user may see;
`VerifyAuthorized` checks only that `authorize` was called.
- A configurable list of trusted proxies for `remote_ip()`.