【问题标题】:jwt auth doesn't work for other controllers in Laravel?jwt auth 不适用于 Laravel 中的其他控制器?
【发布时间】:2021-03-10 14:56:41
【问题描述】:

Laravel 网络身份验证运行良好。 我正在尝试使用 jwt-auth 模块。 这是我的 jwt-auth 模块代码

---authcontroller.php
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            // return response()->json($validator->errors(), 200);
            session()->flash('error', json_encode($validator->errors()));
            return back()->withInput();
        }
        if (!$token = auth()->attempt($validator->validated())) {
            // return response()->json(['error' => 'Unauthorized'], 200);
            session()->flash('error', 'These credentials do not match.');
            return back()->withInput();
        }
        //////// this is test code
        echo auth()->check();
        //////////////////
        $response_token = $this->createNewToken($token);
        session()->flash('token', $response_token);
        return Redirect::to('/');
    }

---web.php

Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'

],
    function ($router) {
        Route::post('/login', [AuthController::class, 'login']);
        Route::post('/register', [AuthController::class, 'register']);
        Route::post('/logout', [AuthController::class, 'logout']);
        Route::post('/refresh', [AuthController::class, 'refresh']);
        Route::get('/user-profile', [AuthController::class, 'userProfile']);
    }
);
---auth.php

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],


    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

问题是 *test 代码返回 true,但在重定向控制器中,auth()->check() 返回 false。 即 auth()->check() 仅在登录控制器时返回 true,而对其他控制器返回 false

有什么问题?

---更新(重定向页面代码)

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>@yield('title')</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">

        <!-- Styles -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />



        <!-- Scripts -->
        <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.7.0/dist/alpine.js" defer></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
        @yield('extra-css')
        <link rel="stylesheet" href="{{ asset('css/style.css') }}">
    </head>
    <body>
        <header>
            <div class="logo">
                <a href="/">
                    <img src="{{ asset('images/blue-logo.png')}}"/>
                </a>
            </div>
            <div class="navigation">
                <a class="mr-3" href="{{ route('audition') }}">Audition</a>
                <a class="mr-3" href="{{ route('about') }}">About</a>
                <a class="mr-3" href="{{ route('playing') }}">Playing</a>
                <a class="mr-3" href="{{ route('faq') }}">Faq</a>
                @if(!auth('api')->check())
                    <a class="mr-3" href="{{ route('login') }}">Login</a>
                    <a class="mr-3" href="{{ route('userType') }}">Register</a>
                @else
                    <a class="mr-3" href="{{ route('support') }}">Support</a>
                    <a class="mr-3" href="{{ route('dashboard') }}">{{ Auth::user()->name }}</a>
                    <form class="d-inline-block" method="POST" action="{{ route('logout') }}">
                        @csrf
                        <a class="mr-3" href="#" onclick="event.preventDefault(); this.closest('form').submit();">Logout</a>
                    </form>
                @endif
            </div>
        </header>
        @yield('content')
        <footer id="footer">
            <ul class="icons">
                <li><a href="#" class="icon brands fa-twitter"><span class="label">Twitter</span></a></li>
                <li><a href="#" class="icon brands fa-instagram"><span class="label">Instagram</span></a></li>
                <li><a href="#" class="icon brands fa-github"><span class="label">GitHub</span></a></li>
                <li><a href="#" class="icon fa-envelope"><span class="label">Email</span></a></li>
            </ul>
            <ul class="copyright">
                <li>&copy; Untitled.</li><li>Credits: <a href="http://html5up.net">HTML5 UP</a></li>
            </ul>
        </footer>
        @yield('extra-js')
    </body>
</html>

【问题讨论】:

    标签: laravel authentication jwt jwt-auth


    【解决方案1】:

    使用auth('api'),因此使用auth('api')-&gt;check()

    auth() 辅助函数默认返回经过身份验证的用户并将其存储在会话和 cookie 中,以便 jwt 或任何其他 api 身份验证方法使用 auth('api') 将检查 Bearer 令牌以及用户是否已通过身份验证.

    【讨论】:

    • 谢谢阿曼。我尝试使用 auth('api') 但登录操作后在登录页面(重定向页面)上仍然是错误的。我添加了重定向页面代码。
    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2014-09-21
    • 2017-05-08
    • 2022-12-04
    • 1970-01-01
    • 2013-10-29
    相关资源
    最近更新 更多