[Python] Session Expiration: React Redux Not Recognizing 401 from Flask

Discussão em 'Python' iniciado por Stack, Outubro 4, 2024.

  1. Stack

    Stack Membro Participativo

    I'm developing a React + Redux application that communicates with a Flask backend. The problem arises when the user's session expires on the Flask server, which results in a 401 Unauthorized response. I want to handle these responses globally in my React app so that when a 401 error occurs, the application resets the user state.

    Even after implementing an Axios interceptor and middleware to catch 401 errors, my application does not recognize when the session expires and consequently does not update the isAuthorized state to false. I want the application to respond appropriately by dispatching a logout action whenever a 401 error is returned from the server.

    I've already did the following:

    const initialState: UserEntity = {
    access_token: '',
    user: null,
    isAuthorized: false,
    tag: '',
    };


    export default {
    'user/authorize': (state: UserEntity, action: PayloadAction<UserEntity>) => {
    state.user = action.payload.user;
    state.isAuthorized = action.payload.isAuthorized;
    state.access_token = action.payload.access_token;
    },
    'UNAUTHORIZED_ACCESS': (state: UserEntity) => {
    state.user = null;
    state.isAuthorized = false;
    state.access_token = '';
    },
    };


    and this below:

    import axios from "axios";
    import { Middleware } from "@reduxjs/toolkit";

    const unauthorizedMiddleware =
    (store: { dispatch: (arg0: { type: string }) => void; getState: () => any; }) =>
    (next: (arg0: any) => any) =>
    (action: any) => {
    if (action.payload && action.payload.status === 401) {
    store.dispatch({ type: "UNAUTHORIZED_ACCESS" });
    return;
    }

    // Axios interceptor for handling 401 errors
    axios.interceptors.response.use(
    (response) => response,
    (error) => {
    if (error.response && error.response.status === 401) {
    store.dispatch({ type: "UNAUTHORIZED_ACCESS" });
    }
    return Promise.reject(error);
    }
    );

    return next(action);
    };

    export default unauthorizedMiddleware;


    How can I ensure that the React application recognizes the 401 Unauthorized response from the Flask backend?

    Is there a better way to manage session expiration and handle user state resets globally in a React + Redux setup?

    Continue reading...

Compartilhe esta Página