Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask JWT extend validity of token on each request

Scenario

A logged in user will have a token expiry of 24 hours. Within that period, all request with @jwt_required decorator will have the current access token's expiry extended by another 24 hours. There is a maximum validity of 168(24 * 7) hours.

It is possible to use access_token and refresh_token.

ret = {
        'access_token': create_access_token(identity=username, fresh=True),
        'refresh_token': create_refresh_token(identity=username)
    }

But that means every API call from my applicatino will be two requests: 1. Actual HTTP Request 2. Refresh the auth token

@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    ret = {
        'access_token': create_access_token(identity=current_user)
    }
    return jsonify(ret), 200

Is there a way to implicitly extend an auth token?

like image 439
Hanxue Avatar asked Sep 13 '17 12:09

Hanxue


People also ask

How do you increase JWT token expiration time in flask?

How do you increase JWT token expiration time in flask? Unfortunately we can't just change the expires time on a JWT on each request, as once a JWT is created it cannot be modified.

How can I extend my JWT token expiry?

To refresh the token, your API needs a new endpoint that receives a valid, not expired JWT and returns the same signed JWT with the new expiration field. Then the web application will store the token somewhere.

How do you handle a JWT token expiry?

So in summary when authorization is successful you need to issue two token ACCESS_TOKEN and REFRESH_TOKEN. When ACCESS_TOKEN expires you need to call another api with REFRESH_TOKEN to get new ACCESS_TOKEN. The client application can get a new access token as long as the refresh token is valid and unexpired.

Does JWT token expire automatically?

The JWT access token is only valid for a finite period of time. Using an expired JWT will cause operations to fail. As you saw above, we are told how long a token is valid through expires_in . This value is normally 1200 seconds or 20 minutes.


1 Answers

app = Flask(__name__)

app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1)
app.config["JWT_REFRESH_TOKEN_EXPIRES"] = timedelta(days=30)
jwt = JWTManager(app)

change time according to your requirement

like image 185
Sushang Agnihotri Avatar answered Oct 09 '22 22:10

Sushang Agnihotri