Authentication/Authorization module¶
Quick Start¶
As of this version, NovaAPI supports authentication and authorization with JWT tokens. To use JWT tokens, it is necessary necessary to set the environment variable JWT_SECRET with the key used to validate the JWS signature and the variable JWT_ALGORITHMS with a comma separated list of the signing algorithms to use. The algorithms must be one of the supported algorithms or they’ll be ignored.
If you are using the file generation functionalities, you may call it with auth_schema=nova_api.JWT to automatically add the JWT validation to all endpoints except health check. This default configuration will only validate exp(expiry timestamp), iat(issued at) and nbf(not before).
You may also use the cli interface generate_nova_api with the option -a JWT to include authentication in the generated API files.
If you are not using the file generation, you may add the following security definition to the end of your api configuration file (for swagger 2.0).
securityDefinitions:
jwt:
type: apiKey
name: Authorization
in: header
x-authentication-scheme: Bearer
x-bearerInfoFunc: nova_api.auth.decode_jwt_token
The x-bearerInfoFunc indicates the function which will validate the token. After adding the definition, you may apply it to an endpoint as follows:
/:
get:
operationId: my_api.read
security:
- jwt: ['secret']
tags:
- "my_tag"
parameters:
...
summary: "Lists all things available"
description: "Lists all things in the database. May be filtered by all fields."
responses:
200:
...
After adding the security option, the JWT decoding will occur before the call to operationId. If you need to validate claims other than those related to emission date and expiration, you may use the validate_jwt_claims decorator. In the next example, we validate if the issuer was novaweb using the iss claim. As of this moment, there is no support for lists of possible values in claims.
from nova_api.auth import validade_jwt_claims
@validate_jwt_claims(claims={"iss":"novaweb"})
def read():
...
If you need to check a claim which needs to be changed dynamically, the best option is to not use the validate_jwt_claims decorator and add the token_info keyword argument to the operation. Remember that it is still necessary to add the security definitions to the yaml file as shown above.
def read(token_info: dict = None):
# Now we can check claims here
if token_info.get("my_claim") == "my_value":
do_something
...
If you have a combination of dynamic and static claims, you may use the add_token_info parameter of the validate_jwt_claims decorator to forward the token info for your operation. You have to add token_info as a keyword argument or **kwargs
from nova_api.auth import validade_jwt_claims
@validate_jwt_claims(claims={"iss":"novaweb"}, add_token_info=True)
def read(token_info: dict = None):
# Now we can check other claims here
if token_info.get("my_claim") == "my_value":
do_something
...
Module Documentation¶
-
nova_api.auth.decode_jwt_token(token: str) → dict[source]¶ Function to decode JWT token.
Decodes JWT Token using JWT_SECRET environment variable as key. During decoding the JWS(signature) is validated along with exp(expiry timestamp), iat(issued at timestamp) and nbf(not before) claims. No other claims are validated and they should be validated with the validate_jwt_claims decorator.
Parameters: token – JWT token base64 encoded and signed Returns: Dictionary of token claims if JWT is valid or raises unauthorized if invalid
-
nova_api.auth.read_decode_algorithms() → list[source]¶ Reads the JWT_ALGORITHMS environment variable and builds the list that should be used as the decoding algorithms for the JWT tokens. This function also validates that the algorithm informed is valid and supported and ignores it otherwise.
Returns: The algorithms list
Aborts API call with status code 401 and message “Unauthorized”
This functions takes any argument as it is used by the auth decorators.
Returns: HTTPException with status code 401
-
nova_api.auth.validate_jwt_claims(add_token_info: bool = False, claims=None)[source]¶ Decorator to authenticate and authorize access to API endpoint
Checks if the received claims are present in token_info and if they match the necessary values. If the decorated function doesn’t have a keyword argument token_info, it will be added by the decorator.
Example
In the following example, if the token_info doesn’t have the iss claim with value “novaweb”, my_endpoint won’t be called.
@validate_jwt_claims(claims = {"iss":"novaweb"}) def my_endpoint(): ...
Parameters: - claims – Dictionary with the necessary claims to authorize the use of the endpoint
- add_token_info – If set to true, token_info will be passed to decorated function as token_info keyword argument.
Returns: Decorated function if token contains correct claims or unauthorize.