Javascript 路由的登录和身份验证(react或服务器端)
我正在尝试保护我在react页面上的表单路由。我在服务器端注册和登录。对于如何对该路由使用身份验证有点困惑 这是我的app.js,我的客户端路由Javascript 路由的登录和身份验证(react或服务器端),javascript,reactjs,express,authentication,password-protection,Javascript,Reactjs,Express,Authentication,Password Protection,我正在尝试保护我在react页面上的表单路由。我在服务器端注册和登录。对于如何对该路由使用身份验证有点困惑 这是我的app.js,我的客户端路由 const App = () => { return ( <Container maxwidh='lg'> <BrowserRouter> <Navbar /> <Grow in> <Container>
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
您正在尝试根据身份验证状态来设置前端路由。因此,您可以创建一个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
}}
/>
)
}
/>
);
}
从'react router dom'导入{Route,Redirect}
导出默认函数privaterout({component:component,…rest}){
const{isAuthenticated}=useAuthentication()
//例如:您可以创建一个react钩子,它将为您提供
//基于您的实现的身份验证详细信息。
返回(
我被认证了(
) : (
)
}
/>
);
}
并使用上述组件设置路由:
...
<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>
...
。。。
//这是现在的保护
...
是,这很有帮助。我仍然不知道如何检查身份验证状态。就像下面示例中的UseAntation()一样,对于我提到的react钩子,例如,UseAntation
,请先尝试以原始方式进行操作,然后如果您认为创建钩子有帮助,可以创建这样的钩子。那么,让我们找出原始的身份验证方法。你是如何认证的?使用?如果是的话,这是否有效(比如说它是否适用)?如果是,您的JWT在哪里?我将使用上述代码中的ensureAuthenticated方法。我的身份验证方法存储在服务器端。我需要从我的客户端访问它吗?