I have 3 views, (Home, signup, login)made in reactJs, I want to use passport in my project but I dont know how to do it, I have passport configurated and it url is working.
Client-side example
import React, { useEffect, useState } from 'react';
import { Link } from "react-router-dom";
import axios from 'axios';
function Home() {
const [loggedIn, setLoggedIn] = useState(false);
useEffect(() => {
axios.get('/checkAuthentication')
.then(res => {
setLoggedIn(res.data.authenticated);
})
.catch((error) => {
setLoggedIn(false)
});
}, []);
return (
<div>
{loggedIn ? (
<p>Login success</p>
) : (
<div>
<Link to="/signup">
Signup
</Link>
<Link to="/login">
Login
</Link>
</div>
)}
</div>
);
}
export default Home;
Server-side example (req.user must be populated if you set up passport)
app.get("/checkAuthentication", (req, res) => {
const authenticated: boolean = typeof req.user !== 'undefined'
res.status(200).json({
authenticated,
});
});
You'll need passport, but in a backend environment with users authentication. Something with node.js+express.js+passport+someDB.
Probably a bit more that what you're asking for, but you can use feathersjs that comes with these built in modules.
With FeathersCli you get user/pass authentication with JWToken in no time by running (after installed):
feathers generate app
then feathers generate authentication
You can Use passport.js with node.js and also can use jsonwebtoken ,i personally use that very usefull simple to code and pretty secure and easily can use to frontend with react or any other frontend framework . The best thing is backend :-> node.js + passport.js + jsonwebtoken frontend :-> react/ any other framework + redux it works really awesome.
you need to create a middleware function where put the code
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()) {
return next()
} else {
res.redirect('/')
}
}
and then use in a router
app.get('/account', ensureAuthenticated, function(req, res){
// here return some data
})
From React probably you have to do a fetch request
fetch('https://your_url/account', {
credentials: 'include'
})
Something like this, you have to make ajax request to the server or by using socket.io or websockets