AUTHORIZE
Require authentication for the endpoint. Optionally specify required roles.
Keywords
authorize, authorized, requires_authorization
Syntax
authorize
authorize <role1> [role2] [role3] ...1
2
2
Examples
Require Any Authenticated User
sql
create function get_my_profile()
returns json
language sql
as $$select row_to_json(u) from users u where u.id = current_user_id()$$;
comment on function get_my_profile() is
'HTTP GET
authorize';1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Unauthenticated requests receive 401 Unauthorized.
Alternative Keywords
sql
-- All of these are equivalent
comment on function func1() is 'HTTP
authorize';
comment on function func2() is 'HTTP
authorized';
comment on function func3() is 'HTTP
requires_authorization';1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Require Specific Role
sql
create function delete_user(_id int)
returns void
language sql
as $$delete from users where id = _id$$;
comment on function delete_user(int) is
'HTTP DELETE
authorize admin';1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Only users with the admin role can access this endpoint.
Multiple Roles
sql
create function manage_content(_action text, _id int)
returns json
language sql
as $$...$$;
comment on function manage_content(text, int) is
'HTTP POST
authorize admin editor moderator';1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Users must have at least one of the specified roles.
Authorize Before HTTP
The order of annotations doesn't matter:
sql
comment on function protected_func() is
'authorize admin
HTTP GET';1
2
3
2
3
Authorize on Separate Line
sql
comment on function another_protected() is
'HTTP
Authorize';1
2
3
4
2
3
4
Behavior
- Returns
401 Unauthorizedfor unauthenticated requests - Returns
403 Forbiddenwhen roles are specified and user lacks required role - Works with all configured authentication providers (JWT, Cookie, Basic, etc.)
Related
- Authentication configuration - Configure authentication providers
- Authentication Options configuration - Configure authentication behavior
- Comment Annotations Guide - How annotations work
- Configuration Guide - How configuration works
Related Annotations
- ALLOW_ANONYMOUS - Override to allow unauthenticated access
- LOGIN - Mark as authentication endpoint
- LOGOUT - Mark as sign-out endpoint