如何确保在React / Redux路由器重定向之前进行JWT验证?

问题描述 投票:0回答:1

我正在使用React / Redux开发一个完整的堆栈PERN应用程序,为数据库使用Knex + Objection.Js + PostgreSQL,为API框架开发Featjs。因此,我在前端使用@feathersjs/client及其身份验证包。我也在使用connected-react-router进行路由。不幸的是,每当我尝试导航到受保护的路由时,负责设置用户状态的“登录”请求(来自他们对服务器进行身份验证的jwt)在重定向将用户带到登录页面之前没有完成。

我通过调度动作来验证反应应用程序的index.js文件中的jwt。

if (localStorage['feathers-jwt']) {
  try {
       store.dispatch(authActions.login({strategy: 'jwt', accessToken: localStorage.getItem('feathers-jwt')}));
  }
  catch (err){
      console.log('authenticate catch', err);
  }
}

该行动由redux-saga接收,执行以下操作

export function* authSubmit(action) {
  console.log('received authSubmit');
  try {
    const data = yield call(loginApi, action);
    yield put({type: authTypes.LOGIN_SUCCESS, data});

  } catch (error) {
      console.log(error);
      yield put({type: authTypes.LOGIN_FAILURE, error})
  }
}

function loginApi(authParams) {
  return services.default.authenticate(authParams.payload)
}

这是我的配置对象的isAuthenticated函数:

const isAuthenticated =  connectedReduxRedirect({
  redirectPath: '/login',
  authenticatedSelector: state => state.auth.user !== null,
  redirectAction: routerActions.replace,
  wrapperDisplayName: 'UserIsAuthenticated'
});

这是应用于容器组件的HOC

const Login = LoginContainer;
const Counter = isAuthenticated(CounterContainer);
const LoginSuccess = isAuthenticated(LoginSuccessContainer);

最后,这是渲染

export default function (store, history) {
  ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <Switch>
          <Route exact={true} path="/" component={App}/>
          <Route path="/login" component={Login}/>
          <Route path="/counter" component={Counter}/>
          <Route path="/login-success" component={LoginSuccess}/>
          <Route component={NotFound} />
        </Switch>
      </ConnectedRouter>
    </Provider>,
    document.getElementById('root')
  );
}

我希望发生什么,登录和访问时,例如,/counter如下

  1. 已触发LOGIN_REQUEST操作
  2. 触发了LOGIN_SUCCESS操作,用户通过JWT进行身份验证
  3. 路由器看到user.auth对象不为null,因此用户已通过身份验证
  4. 路由器允许导航而无需重定向

我所看到的是以下(当手动导航到/counter时)

  1. @@在里面
  2. auth / LOGIN_REQUEST [这很好,loggingIn: true]
  3. @@路由器/ LOCATION_CHANGE
{
  type: '@@router/LOCATION_CHANGE',
  payload: {
    location: {
      pathname: '/counter',
      search: '',
      hash: ''
    },
    action: 'POP',
    isFirstRendering: true
  }
}
  1. @@ router_LOCATION_CHANGE [这是问题]
  type: '@@router/LOCATION_CHANGE',
  payload: {
    location: {
      pathname: '/login',
      hash: '',
      search: '?redirect=%2Fcounter',
      key: 'kdnf4l'
    },
    action: 'REPLACE',
    isFirstRendering: false
  }
}
  1. 用户导航到/login,它会根据当前设计将用户记录下来。
  2. LOGOUT_REQUEST - > LOGIN_SUCCESS - > LOCATION_CHANGE(到/login-success

再次,任何帮助将不胜感激,我可以根据需要提供任何其他帮助。

谢谢!

-Brenden

reactjs redux jwt redux-saga feathersjs
1个回答
0
投票

Solution

今天我能够通过查看认证包feathers-reduxify-authentication的功能来解决这个问题。在大多数情况下,重定向是正确配置的。

BACKEND

authentication.js

注意多个策略,以及如何返回context.result。这对于feathers-reduxify-authentication正常工作是必要的。

module.exports = function (app) {
  const config = app.get('authentication');

  // Set up authentication with the secret
  app.configure(authentication(config));
  app.configure(jwt());
  app.configure(local(config.local));


  app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies),
      ],
      remove: [
        authentication.hooks.authenticate('jwt')
      ]
    },
    after: {
      create: [
        context => {
          context.result.data = context.params.user;
          context.result.token = context.data.accessToken;
          delete context.result.data.password;
          return context;
        }
      ]
    }
  });
};

FRONTEND

SRC /羽/ index.js

这是根据eddystop的示例项目,但升级到羽毛3.0+

import feathers from '@feathersjs/client';
import  io  from 'socket.io-client';
import reduxifyAuthentication from 'feathers-reduxify-authentication';
import reduxifyServices, { getServicesStatus } from 'feathers-redux';
import { mapServicePathsToNames, prioritizedListServices } from './feathersServices';
const hooks = require('@feathersjs/client');

const socket = io('http://localhost:3030');
const app = feathers()
  .configure(feathers.socketio(socket))
  .configure(hooks)
  .configure(feathers.authentication({
    storage: window.localStorage
  }));
export default app;

// Reduxify feathers-client.authentication
export const feathersAuthentication = reduxifyAuthentication(app,
  { authSelector: (state) => state.auth.user}
);
// Reduxify feathers services
export const feathersServices = reduxifyServices(app, mapServicePathsToNames);
export const getFeathersStatus =
  (servicesRootState, names = prioritizedListServices) =>
    getServicesStatus(servicesRootState, names);

中间件和商店。 SRC /州/ configureStore

redux-saga暂时被删除,一旦我完成测试,我会把它带回来

import { createBrowserHistory } from 'history';
import { createStore, applyMiddleware, compose } from "redux";
import { routerMiddleware  } from 'connected-react-router';
import createRootReducer from './ducks';
import promise  from 'redux-promise-middleware';
import reduxMulti from 'redux-multi';
import rootSaga from '../sagas';
import createSagaMiddleware from 'redux-saga';
export default function configureStore(initialState) {

    const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
        || compose;

    const middlewares = [
        //sagaMiddleware,
        promise,
        reduxMulti,
        routerMiddleware(history)];

    const store = createStore(
        createRootReducer(history),
        initialState,
        composeEnhancer(
            applyMiddleware(
                ...middlewares
            )
        )
    );

    return store;
}

root redurs,src / state / ducks / index.js

import { combineReducers } from "redux";
import { connectRouter } from 'connected-react-router';
import { reducer as reduxFormReducer } from 'redux-form';
import {feathersAuthentication, feathersServices} from '../../feathers';
import counter from './counter';

const rootReducer = (history) => combineReducers({
    counter,
    router: connectRouter(history),
    users: feathersServices.users.reducer,
    auth: feathersAuthentication.reducer,
    form: reduxFormReducer, // reducers required by redux-form

});

export default rootReducer;
© www.soinside.com 2019 - 2024. All rights reserved.