React+Laravel using Axios to login doesn't work?

So I'm doing maybe something unorthodox, I'm combining Laravel with React. I and want to use the Laravel Auth system with a react front end.

The problem I am running into is that when I remove the onSubmit part and do a standard form post, to the login function, it works flawlessly, but when I do it with axios, it doesn't actually log me in.

So I have set up a login form like this(hopefully the comments help):


export default class LoginForm extends React.Component
{    
    constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
        this.form = React.createRef();
        this.state = {
            disabled: false,
            email: '',
            password: '',
            csrf: document.head.querySelector('meta[name="csrf-token"]').content,
        }
    }

    onChange(event)
    {
        this.setState({
            [event.target.name] : event.target.value
        });
    }

    onSubmit(e) {
        e.preventDefault();
        //disable the submit button so they can't click more than once
        if(this.state.disabled === false){
            this.setState({ disabled: true });

            //post to the login the request to login
            axios.post(
                '/api/login',
                {
                    _token: this.state.csrf,
                    email: this.state.email,
                    password: this.state.password
                }
            ).then(
                (response) =>
                {
                    // The request was made and the server responded with a status code
                    // that falls inside the 2xx range
                    // Login Successful
                    // Since it's successful we should now be logged in and we can go to the home page.
                    // window.location.href = "/";

                    // For Debugging purposes we're not going to go home just yet
                    this.setState({
                        disabled: false
                    });
                    console.log(response);
                    //our response does come back okay if the email and password is correct
                    //however they are not logged in at this point and I'm not sure why. 
                }
            ).catch(
                (error) => {
                    // The request was made and the server responded with a status code
                    // that falls out of the range of 2xx
                    // Login Failed

                    //remove the disabled state so that the user can try logging in again. 
                    this.setState({
                        disabled: false
                    });
                }
            );
        }
    }

    render(){

        const token = document.head.querySelector('meta[name="csrf-token"]');
        retrun(
            <form name="userRegistrationForm" action="/login" method="POST" onSubmit={this.onSubmit} ref={this.form}>
                <input type="hidden" name="_token" value={token.content} />
                <input type="text" name="email" onChange={this.onChange} maxLength="100" placeholder="Email" required/>
                <input type="password" name="password" onChange={this.onChange} maxLength="100" placeholder="Password" required/>
                <button label="Sign In" loading={this.state.submitted} disabled={this.state.disabled} className={"w-100"}>
                    Sign In
                </button>
            </form>
        )
    }
}

This sends a request via axios to my laravel login controller.

    public function LoginSubmit(Request $request)
    {
        $request->validate([
            'email' => 'required|email|between:1,255',
            'password' => 'required|between:1,255',
        ]);

        $auth = false;
        //get the credentials from the request
        $credentials = $request->only('email', 'password');

        //attempt auth
        if (Auth::attempt($credentials, $request->has('remember'))) {
            $auth = true; // Success
        }

        //if we authed, then login and return
        if ($auth == true) {
            return $this->sendResponse(true);
        } else {
            return $this->sendError(false, "No User found for that email or password does not match");
        }
    }

In theory this should work, the Auth::attempt() should validate the credentials and log the user in. In fact, this works flawlessly when done with the form(by just removing the onSubmit portion entirely) The code for the Laravel form login is almost identical but instead of json responses I do return redirect("/") to go back home.

So is there something I have to do after I get the 200 response from the server to log in the user?

1 answer

  • answered 2019-06-25 19:57 Sabee

    You can use jwt auth (token based authentication) for get token after login. For more information read this post

    config/app.php

    <?php
    'providers' => [
                ....
                Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
                //Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
    ],
    'aliases' => [
    
              ....
              'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    ],
    

    config/jwt.php

    <?php
    return [
        'secret' => env('JWT_SECRET', 'changeme'),
        'ttl' => 60*24*30*6,
        'refresh_ttl' => 20160,
        'algo' => 'HS256',
        'user' => env('JWT_AUTH_TABLE', 'App\User'),
        'identifier' => 'id',
        'required_claims' => ['iss', 'iat', 'exp', 'nbf', 'sub', 'jti'],
        'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', false),
        'providers' => [
            'user' => 'Tymon\JWTAuth\Providers\User\EloquentUserAdapter',
            'jwt' => 'Tymon\JWTAuth\Providers\JWT\Namshi',
            'auth' => 'Tymon\JWTAuth\Providers\Auth\Illuminate',
            'storage' => 'Tymon\JWTAuth\Providers\Storage\Illuminate',
        ],
    ];