简体   繁体   中英

Redirect after login using passport js

I have an aplication where i used react and node js. Also i want to create authentification feature. Register page is working ok, i can get data in node js from fron end. But appears a problem when i try to log in. For log in, in node js, i use passport.js:

 app.post('/login', checkNotAuthenticated, passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login', failureFlash: true } ));

Also i have the Login component in reactjs:

 const Login = () => { const [name, setName] = useState('') const [password, setPassword] = useState('') const nameChange = (e) => { const val = e.target.value; setName(val) } const passwordChange = (e) => { const val = e.target.value; setPassword(val) } const register = (e) => { e.preventDefault() console.log('login: ' + name + password) const data = { name: name, password: password }; const requestOptions = { method: 'post', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify( {name:name,password: password}) }; fetch('http://localhost:4000/login', requestOptions).then((response) => response.json()).then((messages) => {console.log(messages);}); } return ( < div> <h1>Login</h1> <form onSubmit={register}> <input value={name} onChange={nameChange} type="text" placeholder='name' name='name'/> <input value={password} onChange={passwordChange} type="text" placeholder='password' name='password'/> <input type="submit" value='Login'/> </form> </div> ); }; export default Login;

The question is, how to connect front end with node js? How to check when the user is loged with success?

You can use session, something like redis to store user's information in server-side and set a cookie in your client side.

In this way, you should generate a random key and store user's data in redis with that.

'hashed-key' : {//user info in redis}

On every request to server, your client side app send the hash-key with cookie, Nodejs app will check the redis for existence of that key and if everything is OK , it will process the request.

In client side you create a state for your app: member or visitor .

It is a good document for the whole idea "Managing Node.js - Express Sessions with Redis"

It is "Create basic login forms using create react app module in reactjs"

And also read "All You Need to Know About User Session Security"

If you use Express server with ReactJS, you don't have to use redirect option when call passport.authenticate.

Because each environment is different.

So if you redirect to "/" in Express, it will be redirect app.get("/)

you can try like this

app.post('/login', checkNotAuthenticated, (req, res, next) => {
    passport.authenticate('local', (err, user) => {
        if(err) console.error(err);

        req.login(user, loginErr => {
            if(loginErr) {
                console.error(err);
            }

            return res.json(user);
        });
    })(req, res);
});

Then, request from React !

fetch('http://localhost:4000/login', requestOptions)
    .then((response) => response.json())
    .then((user) => { console.log(user); }); // <- Now you get a user!
    .catch(err => console.error(err)); // <- If failed login

if you want to route whether user logged in

try like this

const Router = () => {
    const [user, setUser] = useState(null);

    // when login request success, setUser(user);


    return user ? <Main /> : <Login />;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM