Set up authentication/authorization with flask-jwt-extended + ariadne (graphql) + react

1k views Asked by At

I'm trying to create an auth system for my react(nextjs) app with flask_JWT_extended + ariadne(graphql). I have succesfully set up the login mutation that retrieves the access and refresh token but I dont know how to properly integrate them into my app. I am aware the access token is used to make subsequent requests and the refresh token is used to maintain token freshness but I dont know how to implement it with this stack.

mutations.py

Here is my login mutation that returns the access_token and refresh_token. It works fine.

@mutation.field("login")
@convert_kwargs_to_snake_case
def resolve_login(_, info, username, password):
    user = User.query.filter_by(username=username).first()
    if user and user.check_password(password):
        access_token = create_access_token(identity=username)
        refresh_token = create_refresh_token(identity=username)
        payload = {
            "user": user,
            "access_token": access_token,
            "refresh_token": refresh_token,
        }
   
    return payload

core.py

Here are my JWT configs, from what I have gathered online I am supposed to do a check on the token on each api request to maintain its freshness but I dont know how to do that especially with python + ariadne. Here is a link with someone implementing it with nodejs: https://github.com/benawad/graphql-express-template/blob/22_advanced_jwt_auth/auth.js

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://localhost/pinkle"
app.config["JWT_SECRET_KEY"] = "this_is_a_secret"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
JWTManager(app)

index.js

Here is my front end making the call to login the user, it returns the tokens but I dont know where to utilize the tokens or if I should save it in client side state and just make calls with the token.

function login({ username, password }) {
    axios
        .post('http://localhost:5000/graphql', {
            query: `mutation {
                login(username: "${username}", password: "${password}") {
                    user {
                        id
                        username
                        password
                    }
                }
            }`,
        })
        .then(result => {
            console.log(result.data)
        })
}
1

There are 1 answers

1
vimalloc On

The Flask-JWT-Extended documentation includes examples of utilizing JWTs from JavaScript which might be helpful for you: https://flask-jwt-extended.readthedocs.io/en/stable/token_locations/