路由的登录和身份验证(反应或服务器端)

时间:2021-03-23 12:39:56

标签: javascript reactjs express authentication password-protection

我正在尝试保护我在 React 页面上的表单路由。我在服务器端注册并登录。对如何对该路由使用身份验证有点困惑。

这是我的 app.js,我的客户端路由。

const App = () => {

 
return (
  <Container maxwidh='lg'>
    <BrowserRouter>
      <Navbar />
        <Grow in>
          <Container>
            <div className="content">
              <Switch> 
                <Route path="/" exact component={Home} />
                <Route path="/form" exact component={Form} />
                <Route path="/auth" exact component={Auth} />
                <Route path="/login" exact component={SignIn} />
              </Switch>
            </div>
          </Container>
        </Grow>
      </BrowserRouter>
    </Container>
   );
}
 
export default App;

这些是我的服务器端路由。

import express from 'express';

import { getPosts } from '../controllers/posts.js'
import { createPost, updatePost, deletePost, registerPost } from '../controllers/posts.js'

const router = express.Router();

router.get('/', getPosts);
router.post('/', createPost);
router.patch('/:id', updatePost);
router.delete('/:id', deletePost);

export default router;



export const createPost = async (req, res) => {
    const { title, message, selectedFile, creator, tags } = req.body;

    const newPostMessage = new PostMessage({ title, message, selectedFile, creator, tags })

    try {
        await newPostMessage.save();

        res.status(201).json(newPostMessage );
    } catch (error) {
        res.status(409).json({ message: error.message });
    }
}

这是来自我的 index.js 页面服务器端。

import postRoutes from './routes/posts.js'
import userRoutes from './routes/user.js'
import loginRoutes from './routes/login.js'

const app = express();
dotenv.config();


passportConfig(passport);

app.use(passport.initialize());
app.use(passport.session());

app.use(bodyParser.json({limit: "30mb", extended: true}));
app.use(bodyParser.urlencoded({limit: "30mb", extended: true}));
app.use(cors());

app.use('/posts', postRoutes);
app.use('/auth', userRoutes);
app.use('/login', loginRoutes);

这是我的身份验证页面。

import jwt from 'jsonwebtoken';
import User from '../models/user.js';

const auth = {
    ensureAuthenticated: function(req, res, next) {
        if (req.isAuthenticated()) {
          return next();
        }
        res.redirect('/');
      },
      forwardAuthenticated: function(req, res, next) {
        if (!req.isAuthenticated()) {
          return next();
        }
        res.redirect('/auth');      
      }
}

module.exports = auth

1 个答案:

答案 0 :(得分:1)

您正在尝试根据身份验证状态protect前端路由。因此,您可以创建一个 PrivateRoute 组件,该组件将检查用户是否已通过身份验证,当用户未通过身份验证时,它将重定向/login 路由:

import { Route, Redirect } from 'react-router-dom'

export default function PrivateRoute({ component: Component, ...rest }) {
  const { isAuthenticated } = useAuthentication() 
  // An example: you can create a react-hook which will provide you 
  // authentication details based on your implementation.

  return (
    <Route
      {...rest}
      render={props =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location } 
              // (optional) You can use this location state "from" value to redirect 
              // back the user from /login to the location they were trying
              // to visit before authentication
            }}
          />
        )
      }
    />
  );
}

并使用上面的组件来设置路由:

...
<Switch> 
  <Route path="/" exact component={Home} />
  <PrivateRoute path="/form" exact component={Form} /> // This is now protected
  <Route path="/auth" exact component={Auth} />
  <Route path="/login" exact component={SignIn} />
</Switch>
...