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

问题描述:

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

I am trying to protect my form route on the react page. I register and login on the server side. A little confused about how to use authentication for that route.

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

This is my app.js, my client side routes.

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;

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

These are my server side routes.

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页面服务器端开始的.

This is from my index.js page server side.

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);

这是我的身份验证页面.

This is my authentication page.

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

您正尝试保护前端路由基于身份验证状态.因此,您可以创建一个 PrivateRoute 组件,该组件将检查用户是否已通过身份验证,当用户未通过身份验证时,它将重定向/login 代码>路线:

You are trying to protect frontend routes based on authentication status. So, you can create a PrivateRoute component which will check if the user is authenticated or not and when the user is not authenticated it will redirect to /login route:

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
            }}
          />
        )
      }
    />
  );
}

并使用上述组件来设置路线:

And use above component to setup routes:

...
<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>
...