1

I'm trying to authenticate user in my React application with JWT generated by Spring Boot API. I have problem with getting user info. It returns undefinded
After axios.post call /login I receive response with authorization header. Then I'm storing this token in localStorage, after setting axios.defaults.headers.common['Authorization'] = localStorage.getItem('token'); I call axios.get /user which returns in response username of user assigned to authorization token, again I'm storing response in localStorage. Next thing, I call axios.get /user/{username} to get usersData like id, first name, last name etc..

authService.js

import axios from 'axios';
import { BASE_API_URL } from '../constants/baseURL';

export function login(username, password) {
  axios.post(BASE_API_URL + 'login', { username, password }).then((res) => {
    if (res.data != null) {
      localStorage.setItem('token', res.headers.authorization);
      axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');
      getCurentUsername();
      getCurentUserId();
    }
  });
}

export function getCurentUsername() {
  axios.get(BASE_API_URL + 'user').then((res) => {
    if (res.data != null) {
      localStorage.setItem('username', res.data);
    }
  });
}

export function getCurentUserId() {
  axios.get(BASE_API_URL + 'user/' + localStorage.getItem('username')).then((res) => {
    localStorage.setItem('curentUser', res.data.idUsers);
  });
}

export function logout() {
  localStorage.removeItem('token');
  localStorage.removeItem('username');
  localStorage.removeItem('curentUser');
  delete axios.defaults.headers.common['Authorization'];
}

Login.js

import React, { Component } from 'react';
import { Button, Card, Form, Col } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSave } from '@fortawesome/free-solid-svg-icons';
import { login } from '../services/authService';

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = this.initialState;
    this.credentialsChange = this.credentialsChange.bind(this);
    this.userLogin = this.userLogin.bind(this);
  }

  initialState = {
    username: '',
    password: '',
  };

  userLogin = (e) => {
    e.preventDefault();
    login(this.state.username, this.state.password);
  };

  credentialsChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  render() {
    const { username, password } = this.state;

    return (
      <Card className={'border border-dark bg-dark text-white'}>
        <Card.Header>Sign In</Card.Header>
        <Form onSubmit={this.userLogin} id="loginFormId">
          <Card.Body>
            <Form.Row>
              <Form.Group as={Col} controlId="formGridCountry">
                <Form.Label>Username</Form.Label>
                <Form.Control
                  required
                  autoComplete="off"
                  type="text"
                  name="username"
                  value={username}
                  onChange={this.credentialsChange}
                  className={'bg-dark text-white'}
                  placeholder="Username"
                />
              </Form.Group>
            </Form.Row>
            <Form.Row>
              <Form.Group as={Col} controlId="formGridZipCode">
                <Form.Label>Password</Form.Label>
                <Form.Control
                  required
                  autoComplete="off"
                  type="text"
                  name="password"
                  value={password}
                  onChange={this.credentialsChange}
                  className={'bg-dark text-white'}
                  placeholder="Password"
                />
              </Form.Group>
            </Form.Row>
          </Card.Body>
          <Card.Footer style={{ textAlign: 'right' }}>
            <Button variant="success" type="submit">
              <FontAwesomeIcon icon={faSave} /> Sign In
            </Button>{' '}
          </Card.Footer>
        </Form>
      </Card>
    );
  }
}

export default Login;

localStorage

If I click Sign In button once again localStore curentUser is changing to ID. What did I do wrong? Is it a good way to store data like this? Or maybe use other library like redux to handle it

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Jack B
  • 75
  • 1
  • 6
  • "If I click Sign In button once again localStore curentUser is changing to ID" - sounds like it is working as expected? – T J May 11 '21 at 15:43
  • It doesn't. After first click it sets localStorage curentUser as undefinded. I need to sing in once again to make this work. – Jack B May 11 '21 at 15:50

0 Answers0