Authentication
This tutorial explains how ravnar handles authentication.
A special client is used for the documentation. For real-world scenarios, it can be substituted with a regular HTTP client with the base URL set to the URL of your ravnar deployment.
In [1]:
Copied!
import json
from _ravnar.docs import Client
client = Client()
def print_json(obj):
print(json.dumps(obj, indent=2, sort_keys=False))
import json
from _ravnar.docs import Client
client = Client()
def print_json(obj):
print(json.dumps(obj, indent=2, sort_keys=False))
By default, if no authenticator is configured, authentication is disabled.
In [2]:
Copied!
response = client.get("/api/user").raise_for_status()
print_json(response.json())
response = client.get("/api/user").raise_for_status()
print_json(response.json())
{
"id": "docs",
"data": {},
"permissions": [
"agents:delete",
"agents:read",
"agents:write",
"files:delete",
"files:read",
"files:write",
"threads:delete",
"threads:read",
"threads:write"
]
}
To demonstrate the authentication flow, we use the [ravnar.authenticators.BearerTokenAuthenticator][]
In [3]:
Copied!
from ravnar.authenticators import BearerTokenAuthenticator, User
def token_validator(token: str) -> User:
# validate the token here
return User(id=token)
config = {
"security": {
"authenticator": {
"cls_or_fn": BearerTokenAuthenticator,
"params": {
"token_validator": token_validator,
},
}
}
}
client = Client(config)
from ravnar.authenticators import BearerTokenAuthenticator, User
def token_validator(token: str) -> User:
# validate the token here
return User(id=token)
config = {
"security": {
"authenticator": {
"cls_or_fn": BearerTokenAuthenticator,
"params": {
"token_validator": token_validator,
},
}
}
}
client = Client(config)
With this configuration, ravnar now returns a
401 Unauthorized response when trying to
access any /api endpoint.
In [4]:
Copied!
response = client.get("/api/user")
assert response.status_code == 401
response = client.get("/api/user")
assert response.status_code == 401
To authenticate, the user ID has to be sent as bearer token in the Authorization header
In [5]:
Copied!
user_id = "Huginn"
response = client.get(
"/api/user", headers={"Authorization": f"Bearer {user_id}"}
).raise_for_status()
user = response.json()
print_json(user)
user_id = "Huginn"
response = client.get(
"/api/user", headers={"Authorization": f"Bearer {user_id}"}
).raise_for_status()
user = response.json()
print_json(user)
{
"id": "Huginn",
"data": {},
"permissions": []
}