2
votes

I'm new to Loopback and Reactjs. I wanted to build an application with User login, logout functionality. But, I'm confused how to set the Access Token in Loopback with react front end and further access the other methods. I'm using the User Model provided with Loopback.

So far, I've written this little code, for access login, but I'm confused how to further set the access Token to authenticate.

import React, {Component} from 'react';
import axios from 'axios';

class Login extends Component{

    constructor(props) {
        super(props);
        this.state = {
            "username": ""
            }
        }

    login(newUser) {
        axios.request({
            method:'post',
            url:'http://localhost:3000/api/Users/login',
            data: newUser
          }).then(response => {
            this.props.history.push('/');
          }).catch(err => console.log(err));
    }

    onSubmit(e){
        const newUser = {
            username: this.refs.username.value,
            password: this.refs.password.value
        }
        this.login(newUser);
        e.preventDefault();
    }
}

This code snippet as expected does not set the Access Token, so I was wondering if I require some additional middleware or something to do it.

1
does auth0.login() or window.login() navigate user to auth page with redirecting back on success? - skyboyer
response should return the token if success, you can get the access token by response.id - Jee Mok
@skyboyer oh I'm sorry about that, actually I was attempting to do it with Auth0 and somewhere it went wrong. I edited the current code. - RandomUser

1 Answers

1
votes

try this code.

login(newUser) {
        axios.request({
            method:'post',
            url:'http://localhost:3000/api/Users/login',
            data: newUser
          }).then(response => {
         localStorage.ptspotter_accessToken = response.data.id;
          localStorage.ptspotter_userId = response.data.userId
            auth0.login();
            this.props.history.push('/');
          }).catch(err => console.log(err));
          window.login();
    }

you can store login userId and token in localStorage and access anywhere.