Flask Token-Based Authentication
Clients must send authentication credentials with every request. To avoid having to constantly transfer sensitive information, a token-based authentication solution can be offered.
In token-based authentication, the client sends the login credentials to a special URL that generates authentication tokens. Once the client has a token it can use it in place of the login credentials to authenticate requests. For security reasons, tokens are issued with an associated expiration
The generate_auth_token() method returns a signed token that encodes the users id field. An expiration time given in seconds is also used. The verify_auth_token() method takes a token and, if found valid, it returns the user stored in it. This is a static method, as the user will be known only after the token is decoded.
Improved authentication verification with token support
The first authentication argument can be the email address or an authentication token. If this field is blank, an anonymous user is assumed, as before. If the password is blank, then the email_or_token field is assumed to be a token and validated as such. If both fields are nonempty then regular email and password authentication is assumed
Authentication token generation
Since this route is in the blueprint, the authentication mechanisms added to the before_request handler also apply to it. To prevent clients from using an old token to request a new one, the g.token_used variable is checked, and in that way requests authenticated with a token can be rejected. The function returns a token in the JSON response with a validity period of one hour. The period is also included in the JSON response.