1

How am I able to maintain or create a session through Ajax login. I have a Laravel installation not that much different from a basic make:auth installation.

I had to ovewrite some parts of the authcontroller to return json instead of redirects. Here's the login part:

/**
 * Handle an authentication attempt.
 *
 * @return Response
 */
public function login(Request $request)
{
    $this->validate($request, [
        $this->loginUsername() => 'required',
        'password' => 'required'
    ]);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    $throttles = $this->isUsingThrottlesLoginsTrait();

    if ($throttles && $this->hasTooManyLoginAttempts($request)) {
        // to many attempts
        if ( $request->ajax() )
        {
            $this->response['code'] = 406;
            $this->response['message'] = $this->sendLockoutResponse($request);

            return response()->json($this->response);
        }

        return $this->sendLockoutResponse($request);
    }

    $credentials = $this->getCredentials($request);
    $credentials['is_active'] = 1;

    if (Auth::attempt($credentials, $request->has('remember'))) {
        // succes
        return $this->handleUserWasAuthenticated($request, $throttles);
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    if ($throttles) {
        $this->incrementLoginAttempts($request);
    }

    // error
    if ( $request->ajax() )
    {
        $this->response['code'] = 406;
        $this->response['message'] = $this->getFailedLoginMessage();

        return response()->json($this->response);
    }

    return redirect()->back()
        ->withInput($request->only($this->loginUsername(), 'remember'))
        ->withErrors([
            $this->loginUsername() => $this->getFailedLoginMessage()
        ]);
}

/**
 * Handle an authenticated response.
 *
 * @return Response
 */
public function authenticated($request, $user)
{
    if ( $request->ajax() )
    {
        $this->response['message'] = "success";

        return response()->json($this->response);
    }
    else
    {
        return redirect()->intended($this->redirectPath());
    }
}

Here are the routes used:

Route::group(['namespace' => 'Auth'], function() {
    Route::post('/login', ['uses' => 'AuthController@login', 'as' => 'login']);
    Route::post('/registreer', ['uses' => 'AuthController@postRegister', 'as' => 'register']);
    Route::post('/reset', ['uses' => 'PasswordController@sendResetLinkEmail', 'as' => 'reset']);
});

I am working with Vue.js in the frontend which get the error and succes responses perfectly. Only after refreshing the browser i am not in a logged in state. How am I able to do this.

4
  • Are you building a REST Api? Commented Jul 2, 2016 at 18:49
  • 2
    You should think about to use Tokens instead of setting a Session, take a look at JWT Auth github.com/tymondesigns/jwt-auth Commented Jul 2, 2016 at 19:23
  • No, I am not building a REST Api. I want to create a login form with ajax which adds a nice ui feeling. Like the modal login from airbnb for example. Commented Jul 3, 2016 at 22:48
  • This is something tricky. See laravel.io answer, may this will help you better. Commented Jan 12, 2017 at 12:29

3 Answers 3

1

There's no session when you are working with AJAX / JSON REST APIs. Instead of sessions, REST APIs use tokens / some kind of authentication.

If you are building a REST API and using VueJS as the front end framework for a single page application, use the api middleware instead of the default web middleware.

Read more information about JSON Web Tokens here: https://jwt.io/introduction/

Sign up to request clarification or add additional context in comments.

Comments

0

You are basically creating a stateless application when you are using Ajax. The frontend side basically didnt need to know the state of the user, wether he is already login or not. So you didnt need any session.

What you need to do is get information from the server wether your user is authorized to get any resource on the server. This is basically Authenticating (the process to validate user credential that being sent to the server and then returning sort of id to the user) and Authorization the process to check wether the id is authorized to access the resource requested.

Comments

0

I guess i declared my question not properly because of the misunderstandings. However i did get it to work. The fix is to put middleware around the specific routes. Now I am to login trough a Ajax request.

Route::group(['middleware' => 'web'], function () {
    ...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.