首页 > 解决方案 > Laravel:基于 JWT 的授权,在 Postman 中工作,但不在浏览器中

问题描述

我正在将 JWT 身份验证与 Laravel 5.6 中的博客应用程序集成。

我能够在 Postman 中得到结果。当用户登录但我无法在浏览器中执行相同操作时,我正在尝试重定向到视图(post.blade.php)。

在检查网络中的控制台时,我发现 post.blade.php 路由的状态为 200(OK),但即使在前端我又回到了登录页面(也许没有授权?)

我的前辈建议我使用 ajax 调用进行表单提交,然后将令牌存储在会话或本地存储中。然后在您到达任何路线时调用令牌。我也在做同样的事情。

//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');
        }
    });

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;
}

如果有人可以指导我摆脱这种情况,那将是很大的帮助,拜托!. 自两周以来,我一直在挖掘相同的东西。

标签: phplaraveljwtjwt-authlaravel-jwt

解决方案


推荐阅读