Laravel: JWT based authorization, Working in Postman but NOT in Browser

777 Views Asked by At

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.

0

There are 0 best solutions below