0

I'm integrating the JWT authentication with the Blog application in Laravel 5.6.

I'm able to get the results in Postman. I'm trying to redirect to a view (post.blade.php), when the user is logged in but I'm unable to do the same in Browser.

On checking console in networking, I found that I'm getting status 200 (OK) for post.blade.php route but even though in Frontend I'm getting back to Login page (Maybe not authorizing ?)

My senior suggest me to use the ajax call for form submit and then store the token in session or local storage. and then call for the token whenever you hit any route. I'm doing the same.

//Token Flow ---->

// User submits the credentials
// server verifies the credentials against the DB
// server generates a temporary token and embeds user data into it
// server responds back with the token (in body or header)
// user stores the token in client storage (session or local storage)
// USER SENDS THE TOKEN ALONG WITH EACH REQUEST
// SERVER VERIFIES THE TOKEN & GRANT ACCESS
// when user logs out, token is cleared from the client storage.

Login.blade.php =>

$('[name=login_form]').on('submit', function(event){
    event.preventDefault();
    let email = $('#email').val();
    let password = $('#password').val();

    $.ajax({
        // hitting the below url => which further takes back to login function in authcontroller 
        url: "http://localhost:8000/api/auth/login",
        type: 'POST',
        
        data: {
                email: email,
                password: password
                },
        error: function(err) { console.log('Error!', err) },
        success:function(response){
            //got the token in response from the server for requested creds
            console.log(response); 
            //Now User stores the token in client storage 
            localStorage.setItem('loginToken', response);
            // window.location.replace("http://localhost:8000/api/auth/myposts");  
        },
    }),
    
    $.ajax({
      url: "http://localhost:8000/api/auth/myposts",
      type: 'GET',
      // mode: 'cors',
      headers: {"Authorization": 'Bearer ' + localStorage.getItem('loginToken')},
      success: function(response){
        console.log(response);
        return view('myposts');
        }
    });

Login function in AuthController =>

 public function login(Request $request) {

    $creds = $request->only(['email', 'password']);
    if(! $token = auth('api')->attempt($creds)){
        setcookie('login_cookie', $token, time() + (86400 * 30), "/" );
        return response()->json(['error' => 'Incorrect email/password'], 401);
    }
    $user = auth('api')->userOrFail();
    return $token;
}

It would be great help if someone could guide me to get out of this, please!! . I've been digging around with the same since 2 weeks.

  • have you tried parsing to data to json to send json data to controller – bhucho Dec 10 '20 at 20:31
  • Based on `Login.blade.php`, you are calling both ajax requests at the same time. So the `myposts` request will not have authentication token yet. You need to make the 2nd ajax call inside the `success` callback of the 1st. `$.ajax` calls are asynchronous. – levi Dec 10 '20 at 22:59
  • @bhucho I tried getting the json response also from the login function, But then It was extra effort to parse the token from json response in login blade. – Pankaj Rai Dec 11 '20 at 06:15
  • @levi I agree with your concern. I tried putting the second ajax call inside success of first ajax call, But still i'm getting the same issue. (Network: I get 302 status for login and then it redirects to posts index route without authorizing the user). – Pankaj Rai Dec 11 '20 at 06:19
  • Some one also suggest me to call the second ajax request on another blade page. By redirecting to another page after the login success. But I couldn't figure out how can i do that? – Pankaj Rai Dec 11 '20 at 06:21

0 Answers0