用于生成的 Laravel 护照令牌

Posted

技术标签:

【中文标题】用于生成的 Laravel 护照令牌【英文标题】:Laravel Passport Token for Generation 【发布时间】:2020-02-04 23:11:11 【问题描述】:

第一次尝试护照令牌系统。通过 URL:http://localhost:8000/oauth/token,可以获得访问令牌和刷新令牌。但是,无法在 laravel 控制器文件中使用 oauth/token Post 方法

一些链接: Laravel 5.6 pass oauth/token hanging

Guzzle Cannot make GET request to the localhost (port: 80, 8000, 8080, etc )

namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
use GuzzleHttp\Client;

class AuthController extends Controller



    public function login(Request $request)
    
        $credentials = request(['email', 'password']);
        $credentialsforToken = request(['email', 'password', 'grant_type', 'client_id', 'client_secret']);
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        //$user = $request->user();
        //return $user;
        $http = new Client();
        $response = $http->post(url('oauth/token'), [
            'form_params' => [
                'grant_type' => $credentialsforToken['grant_type'],
                'client_id' => $credentialsforToken['client_id'],
                'client_secret' => $credentialsforToken['client_secret'],
                'username' => $credentialsforToken['email'],
                'password' => $credentialsforToken['password'],
                'scope' => '',
            ],
        ]);
        return json_decode((string) $response->getBody(), true);
```

Access token and Refresh token must be generated

【问题讨论】:

【参考方案1】:

不要使用 Guzzle HTTP 创建内部请求,而是将请求转发到 Passport 路由,并且不要让用户出于安全问题发布客户端密码,例如将它们存储在 env 支持的配置中

我会这样做

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller

    /** @var Response $api_response Response returned from oauth */
    public $api_response = null;
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    public function __construct(Request $request)
    
        $request->request->add([
            'username' => $request->email,
            'grant_type' => 'password',
            'client_id' => '2',
            'client_secret' => config('passport.client_secret'),
            'scope' => '',
        ]);
    

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    
        $validation = $this->validateLogin($request);
        if ($validation->fails()) 
            return response(['error' => $validation->errors()], 401);
        

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) 
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        
        if ($this->attemptLogin($request)) 
            return $this->sendLoginResponse($request);
        

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request)
    
        return Validator::make($request->all(), [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    
        // forward the request to the oauth token request endpoint
        $res = Route::dispatch(request()->create('oauth/token', 'POST', $this->credentials($request)));
        // Set api response for successful login
        $this->api_response = json_decode($res->getContent());
        // Return true or false based on response status code
        return $res->getStatusCode() === 200 ? true : false;
    

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    
        return $request->only('email', 'password', 'grant_type', 'client_id', 'client_secret', 'scope');
    

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    
        return response()->json(['success' => $this->api_response], 200);
    

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Symfony\Component\HttpFoundation\Response
     *
     */
    protected function sendFailedLoginResponse(Request $request)
    
        return response([$this->username() => trans('auth.failed')], 401);
    

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    
        $this->clearLoginAttempts($request);
        return $this->authenticated($request, $this->guard()->user());
    

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    
        $request->user()->token()->revoke();
        return $this->loggedOut($request);
    

这应该是一种功能齐全且安全的方法,希望对您有所帮助

【讨论】:

如何为 Angular 8 API 使用“hasTooManyLoginAttempts”? 后端代码应该与 API 无关,这适用于任何 javascript 框架,hasTooManyLoginAttempts 已包含在我的答案中,对您不起作用? 它包含在代码中,但我使用 Angular 8 作为前端。它不适用于 API 请求? (允许多个 API 请求)

以上是关于用于生成的 Laravel 护照令牌的主要内容,如果未能解决你的问题,请参考以下文章

在内部生成 laravel 护照令牌。 401错误未经授权

Laravel 通过生成的令牌进行身份验证,无需护照和 jwt

Laravel 护照创建令牌和刷新令牌

Laravel 护照刷新令牌

Laravel 护照从数据库中获取令牌

如何使用 Chrome 扩展程序获取 Laravel 护照令牌?