Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
163 views5 pages

ReactJS JWT User Authentication Guide

The document describes how to add user authentication with JWT tokens to a React application. It includes adding a SignIn component with email and password fields that calls an API to log the user in. Upon successful login, the JWT access token is saved to local storage. The SignIn component is rendered on the homepage, and authenticated users are redirected to a Navbar component. An article service fetches data using the JWT token, and routes are set up for the SignIn and Navbar pages.

Uploaded by

driss nadhem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
163 views5 pages

ReactJS JWT User Authentication Guide

The document describes how to add user authentication with JWT tokens to a React application. It includes adding a SignIn component with email and password fields that calls an API to log the user in. Upon successful login, the JWT access token is saved to local storage. The SignIn component is rendered on the homepage, and authenticated users are redirected to a Navbar component. An article service fetches data using the JWT token, and routes are set up for the SignIn and Navbar pages.

Uploaded by

driss nadhem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

JWT avec authentification USER with ReactJS

Ajouter le fichier Components/SignIn.js


import React, { useState } from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useHistory } from 'react-router-dom';

import API from '../Axios/Api';

const useStyles = makeStyles((theme) => ({


 
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '60%',
    marginTop: theme.spacing(1),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
   
  },
   error  :{
    color:'red',
},
}));

1
const SignIn =()=> {
  const classes = useStyles();

  const history = useHistory();


  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const loginUser=()=>{
   
    API.post('/users/login',{
        email,
        password,
    })  
   
    .then((res)=>{
     
      localStorage.setItem("CC_Token",res.data.accessToken);
     
      history.push('/navbar');
     
       
    }).catch(error => {
        toast("Erreur de connexion", {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        });
    });  
  }

const handleSubmit = (event) => {


  console.log(`
    Email : ${email}
    Password : ${password}
   
  `);
 
  event.preventDefault();
}

2
  return (
   

 
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div>
          <ToastContainer />
      </div>
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign in
        </Typography>
        <form className={classes.form} noValidate onSubmit={handleSubmit}>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            autoFocus
            onChange={e => setEmail(e.target.value)}
           
          />
         
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            id="password"
            autoComplete="current-password"
            onChange={e => setPassword(e.target.value)}
          />
           <br/>
          <FormControlLabel
            control={<Checkbox value="remember" color="primary" />}
            label="Remember me"
          />

3
         
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={()=>{loginUser()}}
           
          >
            Sign In
          </Button>
         
          <Grid container>
            <Grid item xs>
              <Link href="#" variant="body2">
               
              </Link>
            </Grid>
           
          </Grid>
        </form>
      </div>
      <Box mt={8}>
       
      </Box>
    </Container>
 
 
 
  );
}
export default SignIn;

Dans le fichier services/Article-service.js

const fetchArticles=async()=> {
        const token = localStorage.CC_Token
       
        return await Axios.get(ARTICLE_API, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer '+token
            },      
        })
 
        }

4
Fichier app.js

import 'bootstrap/dist/css/bootstrap.min.css';

import  Routes  from "./Routes/Routes";

import {BrowserRouter as Router} from "react-router-dom";


const App=() =>{

  return (
   <>
   
   <Router>
 
     
      <Routes/>
     
      </Router>
   </>  
  );
}

Fichier Routes/Routes.js

import Navbarre from "../Components/Navbarre"


import SignIn from "../Components/SignIn";

<Route path="/navbar"  component={Navbarre}/>


<Route path="/"  component={SignIn}/>

You might also like