How can I use passportjs and reactjs together?

后端 未结 4 1563
旧巷少年郎
旧巷少年郎 2021-02-05 08:06

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.

相关标签:
4条回答
  • 2021-02-05 08:50
    • Use componentDidMount/useEffect to get authentication status. Set status in react state.
    • If not authenticated, Show the link to Login/Signup page or redirect.
    • If authenticated, you can return additional protected data or show the link to the protected page.(When showing private data, check authentication status on every page by using componentDidMount/useEffect)

    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,
      });
    });
    
    0 讨论(0)
  • 2021-02-05 08:56

    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

    0 讨论(0)
  • 2021-02-05 09:04

    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.

    0 讨论(0)
  • 2021-02-05 09:09

    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

    0 讨论(0)
提交回复
热议问题