douningqiu4991 2019-08-02 16:26 采纳率: 0%
浏览 111

在Laravel Passport中实现mulit-auth以与VueJS一起使用

I am working on a project where I have two different types of users: Users and Teams. I am doing this in Laravel with VueJs. I have already successfully installed passport, but by default it only authenticates the Users table.

I am at the point in my project where I am implementing the Team Register and Login. I successfully implemented this two sections, however when I login and redirect to the view that contains my root VueJs component and then try to fetch the data of the User, it says that the User is null. However, when I implement a web based "dashboard" and retrieve the user information, I see that I am obviously logged in.

After much research I discovered that my user does not have an access token, which led me to discovering the problem that Passport does not out of the box authenticate all types of users.

I have tried to implement sfelix's multi-auth solution to passport, but it is still not working. I will try to layout everything that I have done as clearly as I can.

My Login for the teams: login.blade.php

  <form method="POST" action="{{ route('login') }}">
                @csrf

                <div class="form-group row pb-3">
                    <label for="Name">Game Code</label>

                    <input id="gameCode" type="gameCode" class="form-control @error('gameCode') is-invalid @enderror" name="gameCode" placeholder="Game Code" required autocomplete="gameCode" autofocus>

                    @error('gameCode')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                    @enderror
                </div>

                <div class="form-group row">
                    <label for="Name">Name</label>

                    <input id="name" type="name" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>

                    @error('name')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                    @enderror
                </div>

                <div class="form-group row">
                    <label for="password">Password</label>

                    <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                    @error('password')
                    <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                    @enderror
                </div>



                <div class="form-group row mb-0">
                    <button type="submit" class="btn btn-primary btn-block">Let's Play!</button>
                </div>
            </form>
        </div>
    </div>

Login route in the TeamLoginController:

public function login(Request $request)
{

    $request->validate([
        'name' =>'required',
        'password' => 'required',
    ]);

    if(Auth::guard('team')->attempt(['name' => $request->name, 'password' => $request->password, 'identifier' => $request->name.$request->gameCode], true)) {
        return redirect()->intended(route('play-lobby'));
    }

    $messages = array(
        'password' => 'Sorry, wrong password :(',
    );

    return Redirect::back()->withErrors($messages);
}

Play Lobby Vue Component:

<template>
    <div>
        <h1>I am the lobby</h1>
    </div>
</template>

<script>
    import {mapActions, mapGetters} from 'vuex';

    export default {
        name: 'Play-Lobby',
        data() {
            return {

            }
        },
        mounted() {
            axios.get('/api/team')
                .then(response => {
                    console.log(response.data);
                });
        },
        methods: {
            ...mapActions('user', ['fetchData']),
            logout(){
                axios.post('/logout')
                    .then(() => {
                        window.location = window.location.protocol + "/login";
                    });
            },
        },
        computed: {
            ...mapGetters('user', ['user']),
        },
    }
</script>

<style scoped>

</style>

The Api/Team Route in the Api.php:

Route::group(['middleware' => ['api', 'multiauth:team-api']], function () {
    Route::get('/team', function (Request $request) {
        return $request->user();
    });
});

What I receive when I enter the play-lobby and console the api route call: enter image description here

Now onto my implementation of multi-auth. Again I followed sfelix's steps, but I may have missed something.

Team Model:

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use SMartins\PassportMultiauth\HasMultiAuthApiTokens;


class Team extends Authenticatable
{
    use HasMultiAuthApiTokens, Notifiable;

    protected $guard = 'team';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

My config/auth.php file:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
        'team' => [
            'driver' => 'session',
            'provider' => 'teams',
        ],
        'team-api' => [
            'driver' => 'passport',
            'provider' => 'teams',
            'hash' => false,
        ],
    ],

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'teams' => [
            'driver' => 'eloquent',
            'model' => App\Team::class,
        ],

My protected middleware in the http/kernel.php:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,

    //what i needed to add
    'oauth.providers' => \SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class,
    'multiauth' => \SMartins\PassportMultiauth\Http\Middleware\MultiAuthenticate::class,

];

my AuthServiceProvider.php:

namespace App\Providers;

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

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();

        // Middleware `oauth.providers` middleware defined on $routeMiddleware above
        Route::group(['middleware' => 'oauth.providers'], function () {
            Passport::routes(function ($router) {
                return $router->forAccessTokens();
            });
        });
    }
}

if anyone could point me in the right direction I would greatly appreciate it.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在炒股软件中,爬到我想看的日k线
    • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序
    • ¥15 多址通信方式的抗噪声性能和系统容量对比
    • ¥15 winform的chart曲线生成时有凸起