Laravel CreateFreshApiToken промежуточное программное обеспечение не работает - PullRequest
0 голосов
/ 06 февраля 2020

Я пытаюсь создать систему аутентификации, используя laravel паспорт и Vue js в качестве приложения-потребителя. Когда я ввожу правильное имя пользователя и паспорт, он возвращает ОК. Но тогда это не создает laravel cook ie. Я даже пытался создать кастомного повара ie. Это не работает как следует. Прежде всего я пробежал php ремесленный паспорт: установить . Это мой middlewareGroup

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

Это мой bootstrap. js файл

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');


if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;    
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

Это мой vue. js логин. vue код

methods:{
        login: function(){
            axios.post('/api/login', {
                username: this.username,
                password: this.password
            }).then(response=>{                                
                console.log(response);
                this.$router.push('/admin');
            }).catch((err)=>{
                console.log(err.response);
            });
        }
    }

Это мой authserviceprovider

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::cookie('c47_c_name');
    }
}

Это мой контроллер входа в систему

<?php

namespace App\Http\Controllers\Users;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
// use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function __construct(){
        //$this->middleware('guest:api')->except('logout');
    }


    public function login(Request $request){    
        $http = new Client();

        try{
            $response = $http->post('localhost:3/oauth/token', [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => '1',
                    'client_secret' => '5jO0SuGVg4u681gvX3I5Lc13rlbPrphaXvJEUFrq',
                    'username'=>$request->username,
                    'password'=>$request->password,                    
                ],
            ]);
            return json_decode((string) $response->getBody(), true);
         } catch (\GuzzleHttp\Exception\BadResponseException $e){
             if($e->getCode() === 400){
                 return response()->json("Invalid request please enter a username and password", $e->getCode());
             } elseif($e->getCode() === 401){
                 return response()->json('Your credentials were incorrent', $e->getCode());
             }

             return response()->json('Something went wrong on the server', $e->getCode());
         }
    }

    public function logout(){

    }
}

Затем, после всего, я пытаюсь получить доступ к этому маршруту


Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Но я получаю исключение 401 Результат в консоли моего браузера

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...