passpost 请求 access_token 步骤报错 401,踩了一车坑,最后报错 401

最近公司新开的项目中使用laravel框架用户登录用的passpost,踩了一车坑,最后报错401,搜索了很多答案不知道该如何解决,救救孩子,先谢过各位了;

下图是本地跑的测试结果,返回401

passpost请求access_token步骤报错401,踩了一车坑,最后报错401

网上搜索401报错说是client_id有问题,以下是.env文件及oauth_clients数据库中的数据
passpost请求access_token步骤报错401,踩了一车坑,最后报错401

passpost请求access_token步骤报错401,踩了一车坑,最后报错401

不确定是什么地方的问题,给大伙上代码康康吧
项目结构大概是这样

passpost请求access_token步骤报错401,踩了一车坑,最后报错401

routes/api.php api路由文件,虽然感觉很有问题,但也说不清楚哪里有问题

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

/**
 * 企业端管理系统路由分组
 */
Route::group([
    'prefix' => 'backend',
], function (Router $router)
{
    $router->get('/', 'Backend\TestController@index');
    $router->post('/upload', 'Backend\TestController@upload');
    $router->post('/login', 'Auth\LoginController@login')->name('backend.login');
    $router->post('/token/refresh', 'Auth\LoginController@refresh')->name('backend.refresh');
    $router->post('/logout', 'Auth\LoginController@logout')->name('backend.logout');
});

/**
 * 用户终端路由分组
 */
Route::group([
    'prefix' => 'frontend',
], function (Router $router)
{
    $router->get('/', 'Frontend\TestController@index');
    $router->get('/getOauthUrl', 'Frontend\WechatController@getOauthUrl');
});

auth.php 中的guards

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

        'backend' => [
            'driver' => 'passport',
            'provider' => 'admin_users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

auth.php中的providers

    'providers' => [
        'admin_users' => [
            'driver' => 'eloquent',
            'model' => App\Models\CompanyAdminUser::class,
            'table' => 'company_admin_users',
        ],

        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
    ],

backend\auth\LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Proxy\TokenProxy;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/home';
    protected $proxy;

    public function __construct(TokenProxy $proxy)
    {
        $this->middleware('guest')->except('logout');
        $this->proxy = $proxy;
    }

    public function username()
    {
        return 'phone';
    }

    protected function guard()
    {
        return Auth::guard('admin_api');
    }

    public function login()
    {
        return $this->proxy->login(request('phone'),request('password'));
    }
}

管理后台用户模型App\Models\CompanyAdminUser

<?php

namespace App\Models;

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

class CompanyAdminUser extends Authenticatable
{
    //指定表名
    protected $table = COMPANY_ADMIN_TABLE;

    use HasApiTokens, Notifiable;

    public function findForPassport($username)
    {
        return $this->where('phone', $username)->first();
    }

    public function validateCredentials(UserContract $user, array $credentials)
    {
        // return $this->hasher->check($plain, $user->getAuthPassword());
        //dd(md5($credentials['password'])==$user->getAuthPassword());
        return md5($credentials['password'])==$user->getAuthPassword();
    }

/app/http/proxy/TokenProxy.php 验证登录文件,这里因为使用auth(‘backend’)->attempt()方法一直报错所以注释掉了

<?php

namespace App\Http\Proxy;

use App\Models\CompanyAdminUser;

class TokenProxy
{
    protected $http;
    const ONE_WEEK_TIME = 3600 * 24 * 7;

    public function __construct(\GuzzleHttp\Client $http)
    {
        $this->http = $http;
    }

    public function login($phone, $password)
    {
        //if (auth('backend')->attempt(['phone'=> $phone, 'password'=> $password])){
        //if (CompanyAdminUser::where('phone',$phone)->where('password',$password)->findOrFail()){

        $user = CompanyAdminUser::where('phone', $phone)->firstOrFail();
        if(md5($password) == $user->password) {
            return $this->proxy('password', [
                'username' => $phone,
                'password' => $password,
                'scope' => '',
            ]);
        }
        return response()->json([
            'status' => 'login error',
            'status_code' => 421,
            'message' => 'Credentials not match'
        ],421);
    }

    public function proxy($grantType, array $data = [])
    {
        $data = array_merge($data, [
            'client_id'     => env('PASSPORT_CLIENT_ID'),
            'client_secret' => env('PASSPORT_CLIENT_SECRET'),
            'grant_type'    => $grantType
        ]);

        $response = $this->http->post(request()->root() . '/oauth/token', ['form_params' => $data
        ]);
        $token = json_decode((string)$response->getBody(), true);
        return response()->json(['token'      => $token['access_token'],
                                 'expires_in' => $token['expires_in']
        ])->cookie('refreshToken', $token['refresh_token'], self::ONE_WEEK_TIME, null, null, false, true);
    }
}

App\Providers\AuthServiceProvider

<?php

namespace App\Providers;

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

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();
        //
        Passport::routes();
        Passport::tokensExpireIn(Carbon::now()->addDays(15));

        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
    }
}

app.php中的providers组件也已经注册

        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        Laravel\Passport\PassportServiceProvider::class,
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 3

太长懒看,,,

https://notes.largezhou.cn/posts/99

给你个链接,我之前尝试 passport 的 DEMO,,,你要是没救了,可以康康

4个月前 评论

file

file 看一下是不是guards选错了

4个月前 评论

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!