1

I am getting token from fetch method in React while I am sending appropriate credentials, but I don't know how to store JWT token in cookie, and later reused it. Also , I don't know why I can't catch the error whenever the login info get wrong.

The token is basiclly like this, click here

Below is code block: Login.js

import React, { Component } from 'react';
import './App.css';
import {
    Button, Card, CardBody, CardGroup, Col, Container, Form, Input,
    InputGroup, InputGroupAddon, InputGroupText, Row
} from 'reactstrap';
class Login extends Component {
    constructor() {
        super();

        this.state = {
            Email: '',
            Password: ''
        }

        this.Password = this.Password.bind(this);
        this.Email = this.Email.bind(this);
        this.login = this.login.bind(this);
    }

    Email(event) {
        this.setState({ Email: event.target.value })
    }
    Password(event) {
        this.setState({ Password: event.target.value })
    }

    login(event) {
        debugger;
        const data = new FormData();
        data.append("username", this.state.Email);
        data.append("password", this.state.Password);
        fetch('https://XXXXXXXX/api/Authenticate/login', {
            method: "POST",
            body: data
        })
            .then(response => response.json())
            .then(result => {
                console.log('Success:', result);
                this.props.history.push("/Dashboard");
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Invalid User');
            });

    }
Choi Ka man
  • 43
  • 1
  • 6
  • Does this answer your question? https://stackoverflow.com/questions/39826992/how-can-i-set-a-cookie-in-react – Lin Du Jan 04 '22 at 02:47

1 Answers1

1

You can store your JWT in browser cookies using this package react-cookie but for more advanced security I suggest using httpOnly cookies.

Paiman Rasoli
  • 1,088
  • 1
  • 5
  • 15