Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用Redux工具包和Typescript设置JWT令牌和基于用户身份验证和角色_Reactjs_Typescript_Redux - Fatal编程技术网

Reactjs 使用Redux工具包和Typescript设置JWT令牌和基于用户身份验证和角色

Reactjs 使用Redux工具包和Typescript设置JWT令牌和基于用户身份验证和角色,reactjs,typescript,redux,Reactjs,Typescript,Redux,回到学校,我编写了这段代码来验证令牌、用户角色和用户身份: 身份验证令牌: const setAuthToken = token => { if (token) { //apply auth token to every request if logged in axios.defaults.headers.common['Authotization'] = token; } else { //delete auth header delete ax

回到学校,我编写了这段代码来验证令牌、用户角色和用户身份: 身份验证令牌:

const setAuthToken = token => {
  if (token) {
    //apply auth token to every request if logged in
    axios.defaults.headers.common['Authotization'] = token;
  } else {
    //delete auth header
    delete axios.defaults.headers.common['Authorization'];
  }
};

export default setAuthToken;
专用线路

const PrivateRoute = ({
  component: Component,
  userRoles = [],
  roles = [],
  auth,
  ...rest
}) => {
  // check the route's roles to see if any match a role the user has
  const hasRole = roles.some(role => userRoles.includes(role));

  return (
    <Route
      {...rest}
      render={props =>
        auth.isAuthenticated === true && hasRole ? (
          <Component {...props} />
        ) : (
          <Redirect to='/' />
        )
      }
    />
  );
};

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  userRoles: state.auth.user.role,
  auth: state.auth
});
export default connect(mapStateToProps)(PrivateRoute);
我的App.js看起来像这样

import routesConfig from './PrivateRoute/routesConfig';

if (localStorage.jwtToken) {
  // Set auth token header auth
  const token = localStorage.jwtToken;
  setAuthToken(token);
  // Decode token and get user info and exp
  const decoded = jwt_decode(token);
  // Set user and isAuthenticated
  store.dispatch(setCurrentUser(decoded));
  // Check for expired token
  const currentTime = Date.now() / 1000; // to get in milliseconds
  if (decoded.exp < currentTime) {
    // Logout user
    store.dispatch(logoutUser());
    // Redirect to login
    window.location.href = './searchVehicles';
  }
}

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Router>
          <div className='App'>
            <Navbar />

            <Switch>
              {routesConfig.routes.map(({ component, roles, url }) =>
                roles.length ? (
                  <PrivateRoute
                    exact
                    path={url}
                    component={component}
                    roles={roles}
                  />
                ) : (
                  <Route exact path={url} component={component} />
                )
              )}
            </Switch>
          </div>
        </Router>
      </Provider>
    );
  }
}
export default App;
从“/privaterout/routeConfig”导入路由配置;
if(localStorage.jwtToken){
//设置身份验证令牌头身份验证
const token=localStorage.jwtToken;
setAuthToken(令牌);
//解码令牌并获取用户信息和exp
const decoded=jwt_decode(令牌);
//设置用户并进行身份验证
存储调度(setCurrentUser(已解码));
//检查过期的令牌
const currentTime=Date.now()/1000;//以毫秒为单位
if(decoded.exp
角色。长度(
) : (
)
)}
);
}
}
导出默认应用程序;
现在我正在使用redux工具包和typescript。。请问有没有更好或更现代的方法来设置?我怎么能用redux套件和ts来做呢

import routesConfig from './PrivateRoute/routesConfig';

if (localStorage.jwtToken) {
  // Set auth token header auth
  const token = localStorage.jwtToken;
  setAuthToken(token);
  // Decode token and get user info and exp
  const decoded = jwt_decode(token);
  // Set user and isAuthenticated
  store.dispatch(setCurrentUser(decoded));
  // Check for expired token
  const currentTime = Date.now() / 1000; // to get in milliseconds
  if (decoded.exp < currentTime) {
    // Logout user
    store.dispatch(logoutUser());
    // Redirect to login
    window.location.href = './searchVehicles';
  }
}

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Router>
          <div className='App'>
            <Navbar />

            <Switch>
              {routesConfig.routes.map(({ component, roles, url }) =>
                roles.length ? (
                  <PrivateRoute
                    exact
                    path={url}
                    component={component}
                    roles={roles}
                  />
                ) : (
                  <Route exact path={url} component={component} />
                )
              )}
            </Switch>
          </div>
        </Router>
      </Provider>
    );
  }
}
export default App;