mercredi 28 août 2019

Allow only authenticated users to access API routes

I want to allow only authenticated users to access some API routes. I use the default Laravel authentication system. After the default login, I want to be able to access a route, but I get the "Unauthenticated" message.

So, after login, I am redirect to the home route which uses the HomeComponent file. Here, using axios, I am making a call to the step API route where I am trying to get the id of the authenticated user, but instead I receive an error message. What am I doing wrong?

api.php

Route::middleware('auth:api')->group(function () {
    Route::get('application/step', ['as' => 'application.step', 'uses' => 'ApplicationController@step']);
});

ApplicationController.php

public function step() {
    print_r(auth()->user());
    die('---');

    // code to get authenticated user step
    return json_encode(array('step' => 7));
}

LoginController.php

public function login(Request $request)
{
    $this->validate($request, [
        'email'   => 'required|email',
        'password' => 'required|min:6'
    ]);

    $user = User::where('email', $request->email)->firstOrFail();
    if ($user && !$user->isAdmin()) {
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password], true)) {
            $token = $user->createToken('TokenName')->token;
            $token->save();

            return redirect()->route('home');
        }
        else {
            return back()->withInput($request->only('email'));
        }
    }

    return back()->withInput($request->only('email'))->withErrors(['denied' => 'You are not allowed to access this page.']);
}

HomeComponent.vue

...
getStep() {
    axios.get("/api/application/step")
         .then((response) => {
             this.step = response.data.step;
         })
         .catch((err) => {
             console.log('Cannot get step', err);
         });
} 



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/340uGaJ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire