Configuration
Property | Description | Default | Type | Required |
---|
enabled | Indicates whether authentication needs to be implemented or not | false | boolean | No |
type | Indicates the type of authentication to implement | local | string | No |
secret | The secret used to sign and decrypt the JWT. Does not apply with Delegated | 52ecfd60e01b800355a8ce59780f9243b4662c3a236394ee | string/object | No |
anonymous | Indicates the body of the Anonymous user in case of no authentication | {"id": "Anonymous", "account": "[email protected]", "name": "Anonymous", "displayName": "Anonymous"} | object | No |
local | Local Authentication |
| Local | No |
ldap | LDAP Authentication |
| LDAP | No |
saml | SAML Authentication |
| SAML | No |
oidc | OIDC Authentication |
| OIDC | No |
delegated | JWKS Authentication |
| Delegated | No |
force_https_original_url_redirection | Force the protocol to https for all original url redirections, when doing authentication | false | boolean | No |
Example Configuration
Code Block |
---|
CONFIG = {
.
.
.
# *******************************************************************************
# Security Configuration
# *******************************************************************************
'security': {
'authentication': {
"enabled": True,
"type": "local",
"secret": "52ecfd60e01b800355a8ce59780f9243b4662c3a236394ee",
"anonymous": {
"id": "Anonymous",
"account": "[email protected]",
"name": "Anonymous",
"displayName": "Anonymous"
},
"local": ...,
"ldap": ...,
"saml": ...,
"oidc": ...,
"delegated": ...
}
}
.
.
.
} |
Attributes Mapping
Anchor |
---|
| AttributesMapping |
---|
| AttributesMapping |
---|
|
Almost every method available in SearchAPI has a property called attributesMapping, this property is used to remap any value in the user data provided by the authentication service into the User data available throughout the server. This transformation is achieved by mapping each key:value pair, where the value is looked up as a key in the user data from the service and remapped with the key in the User data for the server. The original key is kept, as well as any other unspecified values.
Info |
---|
The only required attributes for the attributesMapping are id and account |
Property | Description | Default | Type | Required |
---|
id | Unique identifier for the user |
| string | Yes |
account | User account, usually the same one used for login |
| string | Yes |
roles | User roles, used for access to different sections in the API and UI | [] | array | No |
Tip |
---|
if the attribute roles is remapped, or already exist in the available data, the respective roles will be assigned or will create Roles object managed by the RoleManager |
Cookie Configuration
Property | Description | Default | Type | Required |
---|
name | The name of the cookie used for SAML session management. |
| string | No |
domain | The domain of the cookie used for SAML session management. |
| string | No |
path | The path of the cookie used for SAML session management. | / | string | No |
secure | Whether the cookie used for SAML session management should only be sent over HTTPS. | false | boolean | No |
httpOnly | Whether the cookie used for SAML session management should be accessible only through the HTTP protocol. | true | boolean | No |
sameSite | Specifies the SameSite attribute value of the cookie used for SAML session management. | None | string | No |
Methods
Local
This authentication method uses a CSV file, which involves storing user credentials in a structured format for authentication purposes. In this case, we have a CSV file with the following headers: id, account, password, email, roles, and disabled.
- ID: Unique ID for the user
- Account: User credential necessary for the login
- Password: User password
- Email: User Email
- Roles: List of different role names assigned to each user
- Disabled: Boolean indicating whether the user account is disabled
Note |
---|
It's important to note that using a CSV file for authentication has limitations and may not be suitable for production systems with large user bases. However, it can serve as a simple example or proof of concept. In practice, more robust and secure methods, such as using databases, user directories, or authentication services, are typically employed for user authentication. |
Configuration
Property | Description | Default | Type | Required |
---|
file | CSV file with the definition of the user to have access to the server |
| string | Yes |
Example Configuration
Code Block |
---|
|
'local': {
"file": "/path/to/user.csv"
} |
Example CSV File
Code Block |
---|
|
id,account,password,email,roles,disabled
1,user1,pass123,[email protected],"role1, role2",false
2,user2,pass456,[email protected],"role2, role3",true |
Tip |
---|
There is a CSV file in SearchAPI located in config/auth/users.csv |
LDAP
LDAP (Lightweight Directory Access Protocol) is a widely adopted protocol for accessing and managing directory information services. It is a lightweight, platform-independent, and network-oriented protocol designed for directory services such as user authentication, authorization, and directory information retrieval.
LDAP is based on a client-server model, where a client application interacts with an LDAP server to perform various directory operations. The LDAP server acts as a centralized repository that stores and manages directory entries, which typically represent users, groups, devices, or other resources within an organization.
Configuration
Property | Description | Default | Type | Required |
---|
url | The LDAP server URL. It specifies the network address and protocol (e.g., ldap:// or ldaps://) for connecting to the LDAP server. |
| string | Yes |
authentication | The LDAP authentication method. | SIMPLE | string | Yes |
bindDN | Contains the Distinguished Name (DN) used for binding or authenticating with the LDAP server. |
| string | Yes |
bindCredentials | Contains the password or credentials associated with the bindDN. |
| string | Yes |
searchBase | Specifies the base DN from which LDAP searches should begin. |
| string | Yes |
searchFilter | Represents the LDAP search filter used to narrow down the search results based on specific criteria. |
| string | Yes |
searchAttributes | Specifies the attributes to be returned in the search results. |
| array | No |
tlsOptions | Contains TLS (Transport Layer Security) options for establishing a secure connection with the LDAP server. |
| object | No |
bindProperty | Specifies the LDAP attribute used for binding or authenticating with the LDAP server. |
| string | No |
groupDnProperty | Represents the LDAP attribute used to identify the distinguished name (DN) of a group. |
| string | No |
groupSearchBase | Specifies the base DN from which group searches should begin. |
| string | No |
groupSearchFilter | Represents the LDAP search filter used to narrow down the search results for groups based on specific criteria. |
| string | No |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service, into the User data available throughout the server. |
| AttributesMapping | Yes |
Example Configuration
Code Block |
---|
|
'ldap': {
"url": "ldap://ldap.example.com",
"authentication": "SIMPLE",
"bindDN": "cn=admin,dc=example,dc=com",
"bindCredentials": "password123",
"searchBase": "ou=users,dc=example,dc=com",
"searchFilter": "(objectClass=person)",
"searchAttributes": ["cn", "email"],
"tlsOptions": {
"certificateVerification": true,
"cipherSuites": ["TLS_RSA_WITH_AES_256_CBC_SHA256"],
"clientCertificate": "/path/to/client_certificate.pem",
"clientKey": "/path/to/client_key.pem"
},
"bindProperty": "uid",
"groupDnProperty": "memberOf",
"groupSearchBase": "ou=groups,dc=example,dc=com",
"groupSearchFilter": "(objectClass=group)",
"attributesMapping": {
"id": "uid",
"account": "sAMAccountName",
"roles": ["role1", "role2"]
}
}
|
SAML
Warning |
---|
Removed in version 1.1 |
SAML2 (Security Assertion Markup Language 2.0) authentication is a standard protocol used for exchanging authentication and authorization data between a Service Provider (SP) and an Identity Provider (IdP). It enables secure single sign-on (SSO) functionality, allowing users to authenticate once with the IdP and access multiple services provided by different SPs without the need to re-enter credentials.
Configuration
Property | Description | Default | Type | Required |
---|
strict | If strict is True, then the Python Toolkit will reject unsigned or unencrypted messages if it expects them to be signed or encrypted. Also, it will reject the messages if the SAML standard is not strictly followed. Destination, NameId, Conditions, etc. are validated too. | false | boolean | No |
debug | Controls the debugging mode. When set to True, additional debug information will be logged during SAML processing. | false | boolean | No |
entity_id | Globally unique identifier for the entity and is typically a URL that represents the identity provider or service provider. |
| string | Yes |
single_sign_on_service_url | The single SignOn Service URL for SAML2. |
| string | Yes |
single_sign_on_service_binding | The single SignOn Service Binding for SAML2. | urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect | string | No |
single_logout_service_url | The single Logout Service URL for SAML2. |
| string | Yes |
single_logout_service_binding | The single Logout Service Binding for SAML2. | urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect | string | No |
callback_url | The callback URL for SAML authentication. | http://localhost:8085/es/auth/saml/callback | string | No |
x509cert_path | Path to the public X.509 certificate of the Service Provider, used for signing requests or encrypting assertions. It should be provided in PEM format. |
| string | No |
x509cert | The raw public X.509 certificate of the Service Provider, used for signing requests or encrypting assertions. |
| string | No |
cert_fingerprint | Instead of using the whole X.509 cert, you can use a fingerprint in order to validate a SAMLResponse (but you still need the X.509 cert to validate LogoutRequest and LogoutResponse using the HTTP-Redirect binding). |
| string | No |
cert_fingerprint_algorithm | Algorithm to use in the cert_fingerprint. | sha1 | string | No |
security | SAMLAuthSecurityConfig (Declared below) |
| SAMLAuthSecurityConfig | No |
cookie | Cookie configuration to store the JWT with the current session. |
| CookieConfig | No |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service into the User data available throughout the server |
| AttributesMapping | No |
json_redirect | Redirect to the third party sent as a JSON response. Useful when working with (single-page application) | false | boolean | No |
SAML Security Configuration
Anchor |
---|
| SAMLAuthSecurityConfig |
---|
| SAMLAuthSecurityConfig |
---|
|
Property | Description | Default | Type | Required |
---|
nameIdEncrypted | Indicates that the nameID of the <samlp:logoutRequest> sent by this SP will be encrypted. | false | boolean | No |
authnRequestsSigned | Indicates whether the <samlp:AuthnRequest> messages sent by this SP will be signed. [Metadata of the SP will offer this info] | false | boolean | No |
logoutRequestSigned | Indicates whether the <samlp:logoutRequest> messages sent by this SP will be signed. | false | boolean | No |
logoutResponseSigned | Indicates whether the <samlp:logoutResponse> messages sent by this SP will be signed. | false | boolean | No |
signMetadata | Sign the Metadata | false | boolean or object | No |
wantMessagesSigned | Indicates a requirement for the <samlp:Response> , <samlp:LogoutRequest> , and <samlp:LogoutResponse> elements received by this SP to be signed. | false | boolean | No |
wantAssertionsSigned | Indicates a requirement for the <saml:Assertion> elements received by this SP to be signed. [Metadata of the SP will offer this info] | false | boolean | No |
wantAssertionsEncrypted | Indicates a requirement for the <saml:Assertion> elements received by this SP to be encrypted. | false | boolean | No |
wantNameId | Indicates a requirement for the NameID element on the SAMLResponse received by this SP to be present. | true | boolean | No |
wantNameIdEncrypted | Indicates a requirement for the NameID received by this SP to be encrypted. | false | boolean | No |
wantAttributeStatement | Indicates a requirement for the AttributeStatement element. | true | boolean | No |
requestedAuthnContext | Set to false and no AuthContext will be sent in the AuthNRequest, Set true or don't present this parameter and you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'. Set an array with the possible auth context values: array ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509') | true | boolean | No |
requestedAuthnContextComparison | Allows the authn comparison parameter to be set, defaults to 'exact' if the setting is not present. | exact | string | No |
failOnAuthnContextMismatch | Set to true to check that the AuthnContext(s) received match(es) the requested. | false | boolean | No |
metadataValidUntil | Provide the desired TimeStamp, for example 2015-06-26T20:00:00Z | string |
| No |
metadataCacheDuration | Provide the desired Duration, for example PT518400S (6 days) | string |
| No |
allowSingleLabelDomains | If enabled, URLs with single-label-domains will be allowed and not rejected by the settings validator (Enable it under Docker/Kubernetes/testing env, not recommended on production) | false | boolean | No |
signatureAlgorithm | Algorithm that the toolkit will use on the signing process. | http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 | string | No |
digestAlgorithm | Algorithm that the toolkit will use on the digest process. | http://www.w3.org/2001/04/xmlenc |
| No |
Example Configuration
Code Block |
---|
|
'saml': {
"strict": False,
"debug": False,
"json_redirect": False,
"entity_id": "https://your-idp.com/entity",
"single_sign_on_service_url": "https://your-idp.com/sso",
"single_sign_on_service_binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
"single_logout_service_url": "https://your-idp.com/slo",
"single_logout_service_binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
"callback_url": "http://your-app.com/auth/saml/callback",
"x509cert_path": "/path/to/certificate.pem",
"x509cert": "-----BEGIN CERTIFICATE-----\n...certificate content...\n-----END CERTIFICATE-----",
"cert_fingerprint": "AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01",
"cert_fingerprint_algorithm": "sha256",
"security": {
"nameIdEncrypted": False,
"authnRequestsSigned": False,
"logoutRequestSigned": False,
"logoutResponseSigned": False,
"signMetadata": False,
"wantMessagesSigned": False,
"wantAssertionsSigned": False,
"wantAssertionsEncrypted": False,
"wantNameId": True,
"wantNameIdEncrypted": False,
"wantAttributeStatement": True,
"requestedAuthnContext": True,
"requestedAuthnContextComparison": "exact",
"failOnAuthnContextMismatch": False,
"metadataValidUntil": "2023-12-31T23:59:59Z",
"metadataCacheDuration": "PT24H",
"allowSingleLabelDomains": False,
"signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
"digestAlgorithm": "http://www.w3.org/2001/04/xmlenc#sha256",
"allowRepeatAttributeName": False,
"rejectDeprecatedAlgorithm": True
},
"cookie": {
"max_age": 12,
"expires": 12,
"path": "/es",
"domain": os.getenv("COOKIE_DOMAIN_NAME"),
"secure": False,
"httponly": False,
"samesite": "lax"
},
"attributesMapping": {
"id": "userID",
"account": "email",
"roles": ["role1", "role2"]
}
} |
OIDC
OIDC (OpenID Connect) authentication is an authentication protocol built on top of the OAuth 2.0 framework. It provides a standardized way for clients (relying parties) to authenticate users by leveraging an Identity Provider (IdP).Configuration
Configuration
Property | Description | Default | Type | Required |
---|
client_id | A unique identifier assigned to the client application by the IdP. It identifies the client application during authentication and authorization requests. |
| string | Yes |
openid_configuration_uri | URI to the OpenID Connect configuration values from the provider's Well-Known Configuration Endpoint |
| string | Yes |
callback_url | The URL to which the IdP will redirect the user after successful authentication. It must match one of the registered redirect URIs for the client application. | http://localhost:8085/es/auth/oidc/callback | string | No |
scope | Defines the permissions or claims requested by the client application. It may include values like openid (required for OIDC), profile , email , offline_access , or custom scopes defined by the IdP. | ["openid", "email", "profile"] | array of strings | No |
cookie | Cookie configuration to store the JWT with the current session |
| CookieConfig | Yes |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service, into the User data available throughout the server. The way it serves is for each key:value looks for the value as a key in the user data from the service, and remaps it with the key in the User data for the server. The original key is kept as well as any other non-specified value. |
| AttributesMapping | Yes |
json_redirect | Redirect to the third party sent as a JSON response. Useful when working with (single-page application) | false | boolean | No |
Example Configuration
Code Block |
---|
|
'oidc': {
"client_id": "your-client-id",
"openid_configuration_uri": "https://your-provider.com/.well-known/openid-configuration",
"callback_url": "http://localhost:8085/es/auth/oidc/callback",
"json_redirect": False,
"scope": ["openid", "email", "profile"],
"cookie": {
"max_age": 12,
"expires": 12,
"path": "/es",
"domain": os.getenv("COOKIE_DOMAIN_NAME"),
"secure": False,
"httponly": False,
"samesite": "lax"
},
"attributesMapping": {
"id": "sub",
"account": "email",
"roles": ["role1", "role2"]
}
} |
Delegated (JWKS)
Delegated is a JWT validation with JWKS (JSON Web Key Set) involves verifying the authenticity and integrity of a JWT by using public keys obtained from the IdP's JWKS endpoint.By utilizing JWKS for JWT validation, the client can ensure that the token was issued by a trusted party (IdP) and has not been tampered with. The use of public keys enables cryptographic verification, as only the corresponding private key held by the IdP can produce a valid signature for the JWT.
Configuration
Property | Description | Default | Type | Required |
---|
debug | Debug mode flag | false | boolean | No |
jwks_url | JWKS (JSON Web Key Set) URL is a location where public keys used for verifying JSON Web Tokens (JWTs) can be retrieved |
| string | No |
audience | It specifies the entity or service for which the JWT is issued. The audience claim helps ensure that JWTs are only accepted by the intended recipients, providing an extra layer of security |
| string | No |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service into the User data available throughout the server |
| AttributesMapping | Yes |
Example Configuration
Code Block |
---|
|
'delegated': {
"debug": False,
"jwks_url": "https://your-idp.com/.well-known/jwks.json",
"audience": "your-service-audience",
"attributesMapping": {
"id": "sub",
"account": "email",
"roles": ["role1", "role2"]
}
} |
Encryption
The Encryption section of the SearchAPI project documentation provides an overview of the encryption functionalities implemented within the project. Encryption is a vital aspect of securing sensitive data, ensuring its confidentiality and integrity.
This section focuses on two essential functions: encrypt
and decrypt
. These functions are part of the utils.crypto
module and provide convenient encryption and decryption capabilities for developers working on the SearchAPI project.
Configuration
Property | Description | Type | Required |
---|
secret_key | Piece of information or parameter that is used to encrypt and decrypt messages in a symmetric. The size of the secret key should be no less than 32 characters. If no secret key is specified, one will be created in the config/auth folder | string/file-path | Yes |
Example Configuration
This section provides an overview of the encryption mechanisms used in the SearchAPI project to secure sensitive data during transit and at rest.
Code Block |
---|
|
'encryption': {
"secret_key": "/path/to/secret.key"
} |
or
Code Block |
---|
|
'encryption': {
"secret_key": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
} |
Tip |
---|
If no secret_key is specified, a new secret key will be automatically generated and saved in the config/auth folder. |
Note |
---|
Please note that the secret_key property can either be a file path (string with format "file-path") or a string value. Ensure that the secret key is secure and has a sufficient length for encryption purposes. |
Inner Crypto Module (utils.crypto)
The utils.crypto
module provides various encryption and cryptographic utility functions used within the SearchAPI project. These functions are designed to ensure the security and integrity of sensitive data. This document outlines the available functions and their usage.
Hashing Functions
hash_sha256
This function computes the SHA-256 hash of the input data and returns it as a hexadecimal code. The data
parameter can be either a string or a byte array. The returned hash value is a string.
hash_sha1
This function computes the SHA-1 hash of the input data and returns it as a hexadecimal code. The data
parameter can be either a string or a byte array. The returned hash value is a string.
Generating Keys and Initialization Vectors (IV)
generate_iv
This function generates a random Initialization Vector (IV) of 16 bytes. The IV is used for encryption and decryption processes and ensures the uniqueness and unpredictability of encrypted data.
generate_secret_key
This function generates a secret key of the specified size
(default is 32 bytes). The secret key is used for encryption and decryption. The returned key is a base64-encoded string.
Encryption and Decryption
is_encrypted
This function checks whether the given text
is encrypted. It returns True
if the text has the expected encryption prefix ("encrypted:").
encrypt
This function encrypts the provided text
using AES encryption. If an initialization vector (iv
) is not provided, a random IV is generated. The encrypted text is returned with the prefix "encrypted:" and includes the IV and ciphertext.
decrypt
This function decrypts the given text
using AES decryption. If the text is not encrypted (does not have the encryption prefix), it returns the original text. Otherwise, it extracts the IV and ciphertext from the encrypted text and performs decryption to obtain the original plaintext.
Usage
To use the functions from utils.crypto
, you can import them as follows:
Code Block |
---|
|
from utils.crypto import hash_sha256, hash_sha1, generate_iv, generate_secret_key, is_encrypted, encrypt, decrypt
|
You can then call the functions according to your requirements. For example:
Code Block |
---|
|
data = "Hello, World!"
# Compute SHA256 hash
hash_value = hash_sha256(data)
print(f"SHA256 hash: {hash_value}")
# Generate a random IV
iv = generate_iv()
print(f"Generated IV: {iv}")
# Generate a secret key
secret_key = generate_secret_key()
print(f"Generated secret key: {secret_key}")
# Check if a text is encrypted
encrypted_text = encrypt(data)
is_text_encrypted = is_encrypted(encrypted_text)
print(f"Is the text encrypted? {is_text_encrypted}")
# Decrypt the encrypted text
decrypted_text = decrypt(encrypted_text)
print(f"Decrypted text: {decrypted_text}") |
Tip |
---|
By utilizing the functions provided in utils.crypto , you can enhance the security and encryption capabilities within the SearchAPI project. |
Roles
This configuration allows to add additional role for role verification using a CSV file. The file should contain the following headers:
- ID: Unique ID for the role
- Role: Display name of the role
- Value: Numeric value assigned to the role for hierarchical comparisons
These roles are later loaded into the RoleManager
, which by default has five roles defined: UNAUTHORIZED, ANONYMOUS, USER, ADMIN, READ_ONLY.
Note |
---|
Ensure that the CSV file specified in the file property follows the correct format and contains the necessary role definitions. |
Configuration
Property | Description | Type | Required |
---|
file | CSV file with the definition of the roles. The file should have the following headers: ID, Role, Value. | string/file-path | Yes |
Example Configuration
Code Block |
---|
|
'roles': {
"file": "/path/to/roles.csv"
}
|
Example Role CSV
Code Block |
---|
|
ID,Role,Value
1,Admin,100
2,User,50
3,Guest,10
|
Role Manager
The RolesManager class is responsible for managing roles within the SearchAPI project. It allows the creation, retrieval, and modification of roles.
Usage
To use the RolesManager
, you can import anywhere in the code as follows:
Code Block |
---|
|
from models.security import roles_manager |
Creating Roles
The RolesManager
class provides the get_or_create
method to create and retrieve roles. You can create a new role or get an existing one using the get_or_create
method.
Code Block |
---|
|
# Create or get the "user" role
user_role = roles_manager.get_or_create(id="user", name="User", value=10)
# Create or get the "admin" role
admin_role = roles_manager.get_or_create(id="admin", name="Admin", value=100) |
If a role with the specified id
already exists, it will be retrieved. Otherwise, a new role will be created.
Retrieving Roles
To retrieve a role by its id
, you can use the get_role
method:
Code Block |
---|
|
# Get the "user" role
user_role = roles_manager.get_role("user")
# Get the "admin" role
admin_role = roles_manager.get_role("admin") |
If the specified role does not exist, a new role with the provided id
will be created and returned.
Modifying Roles
The RolesManager
class allows you to overwrite the properties of an existing role using the overwrite_role
method:
Code Block |
---|
|
# Create a new role
custom_role = Role(id="custom", name="Custom Role", value="custom_value")
# Overwrite the "user" role with the custom role
roles_manager.overwrite_role(custom_role) |
or
Code Block |
---|
|
# Create or get the "user" role
user_role = roles_manager.get_role("user")
# Overwrite the "user" role with the new values
admin_role = roles_manager.get_or_create(id="user", name="User", value=50, overwrite=True) |
Note |
---|
If the role with the specified id already exists, its name and value properties will be updated with the values from the custom_role object. |
Predefined Roles
The RolesManager
class also defines several predefined roles as class attributes:
UNAUTHORIZED
: Represents an unauthorized role.ANONYMOUS
: Represents an anonymous role.USER
: Represents a user role.ADMIN
: Represents an admin role.READ_ONLY
: Represents a read-only role.
These roles can be accessed directly from the RolesManager
instance:
Code Block |
---|
|
# Access the predefined roles
unauthorized_role = roles_manager.UNAUTHORIZED
anonymous_role = roles_manager.ANONYMOUS
user_role = roles_manager.USER
admin_role = roles_manager.ADMIN
read_only_role = roles_manager.READ_ONLY |
By utilizing the RolesManager
class, you can easily create, retrieve, and modify roles within the SearchAPI project.
Role API Verification
The RoleVerifications class is a dependency class designed for FastAPI. It provides role-based authorization checks for user requests. This documentation describes the available methods and their usage.
Usage
To use the RoleVerifications
class, you can create an instance of it with the desired roles:
Code Block |
---|
|
role_verifications = RoleVerifications(roles=[roles_manager.ADMIN, roles_manager.READ_ONLY, roles_manager.get('Support')]) |
or
Code Block |
---|
|
# Declared directly in the route with the verification type
@router.get('/route', dependencies=[RoleVerifications([roles_manager.ADMIN, roles_manager.READ_ONLY, roles_manager.get('Support')]).requires_all()]) |
requires_any
The requires_any
method allows access to users with any of the defined roles.
Code Block |
---|
|
@router.get("/route")
async def route_handler(user: User = role_verifications.requires_any()):
# Handle route logic
|
Note |
---|
If the user has all of the specified roles, a 403 Forbidden HTTP exception will be raised. |
requires_all
The requires_all
method allows access to users who have all of the defined roles.
Code Block |
---|
|
@app.get("/route")
async def route_handler(user: User = role_verifications.requires_any()):
# Handle route logic
|
Note |
---|
If the user has all of the specified roles, a 403 Forbidden HTTP exception will be raised. |
forbid_any
The forbid_any
method forbids access to users with any of the defined roles.
Code Block |
---|
|
@router.get("/route")
async def route_handler(user: User = role_verifications.requires_any()):
# Handle route logic
|
Note |
---|
If the user has all of the specified roles, a 403 Forbidden HTTP exception will be raised. |
forbid_all
The forbid_all
method forbids access to users who have all of the defined roles.
Code Block |
---|
|
@router.get("/route")
async def route_handler(user: User = role_verifications.requires_any()):
# Handle route logic |
Note |
---|
If the user has all of the specified roles, a 403 Forbidden HTTP exception will be raised. |
By utilizing the methods provided by the role verification, you can enforce role-based authorization checks in your FastAPI routes, ensuring that only users with the required roles can access the protected endpoints.
This configuration allows to add additional headers on Search API's responses.
Note |
---|
The headers added in this way are going to be added to all of the responses, hence it's recommended for security headers like the Strict Transport Security headers and others of such nature. |
Configuration
Property | Description | Type | Required |
---|
include | List of tuples representing header name and its value. | list[Tuple[str, str]] | False |
Example Configuration
Code Block |
---|
|
'headers': {
'include': [
('strict-transport-security', 'max-age=31536000;includeSubDomains')
]
}
|