miguelgrinberg / microblog-api

A modern (as of 2024) Flask API back end.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Tokens

hackzaid opened this issue · comments

When you create a new token, is it just my code or something wrong with codebase that the refresh token returns as a null value?

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.........",
  "refresh_token": null
}

And when revoking the access_token, I always get this error:

return _unicodify_header_value(self.environ[f"HTTP_{key}"])
KeyError: 'HTTP_AUTHORIZATION'

Can't seem to find where it's originating from.

The revoking now works after modifying the endpoint to this:

@tokens.route('/tokens', methods=['DELETE'])
@authenticate(token_auth) <<< added this line here
@response(EmptySchema, status_code=204, description='Token revoked')
@other_responses({401: 'Invalid access token'})
def revoke():
    """Revoke an access token"""

Is this a recommended way or there is a better way to handling revoking tokens?

Without the code I have no way to know what to debug this problem. This is the APIFairy project, which is generic and has nothing to do with tokens. You seem to be asking about a project in particular, maybe something based on my microblog-api example?

Clearly @miguelgrinberg I am expanding my project from the microblog-API example.

This is the endpoint that handles "create access and refresh tokens" as copied from the microblog-API project

@tokens.route('/tokens', methods=['POST'])
@authenticate(basic_auth)
@response(token_schema)
@other_responses({401: 'Invalid username or password'})
def new():
    """Create new access and refresh tokens

    The refresh token is returned in the body of the request or as a hardened
    cookie, depending on configuration. A cookie should be used when the
    client is running in an insecure environment such as a web browser, and
    cannot adequately protect the refresh token against unauthorized access.
    """
    user = basic_auth.current_user()
    token = user.generate_auth_token()
    db.session.add(token)
    Token.clean()  # keep token table clean of old tokens
    db.session.commit()
    return token_response(token)

Okay, I think I understand. I agree, it makes sense to add the @authenticate decorator on the revoke token endpoint. It isn't strictly necessary, but from an OpenAPI standpoint it should be added so that the documentation reflects that the token is required. Will go ahead and add it.

Sorry, forgot to reply to that.

I suggest you read the code to understand how refresh tokens work (and the documentation for the endpoint). These can be returned in the body of the response, or in a secure cookie. You must have your application configured to return it in the secure cookie, which is more secure.