我可以使用带有laravel的auth结构的api进行身份验证吗?

时间:2018-04-16 13:39:41

标签: php laravel oauth-2.0 laravel-passport

我想在前端和管理面板上使用一个API,使用Laravel auth结构(使用make:auth)和API身份验证(使用Passport)来管理所有操作操作。

我的“routes / api.php”文件;

Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'as' => 'api.admin.'], function () {
    Route::post('login', 'Auth\LoginController@login')->name('login');
    Route::post('logout', 'Auth\LoginController@logout')->name('logout');

    Route::group(['middleware' => 'auth:api'], function () {
        //
    });

});

我的Auth \ LoginController文件;

<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | 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;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }

    public function logout(Request $request)
    {
        auth()->logout();
        session()->flash('message', 'Some goodbye message');
        return redirect()->route('admin.login');
    }
}

当我使用post方法和“email”,“password”数据调用“/ api / admin / login”url时,它返回以下错误;

RuntimeException
Session store not set on request.

我认为在Kernel.php api组的$ middlewareGroup中使用以下方法解决了上述错误; 我的app / Http / Kernel.php文件;

\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class

会话存储未按请求设置。错误已解决,但现在返回MethodNotAllowedHttpException。

我可以用其他方法解决这些问题,但我想使用Laravel的auth标准。

这可能吗?

谢谢大家。

2 个答案:

答案 0 :(得分:1)

虽然它比仅仅切换登录URL更有可能,但它是可能的。您将使用Password Grant Flow,因此用户可以使用现有的电子邮件和密码凭据进行身份验证。

您无需启用会话即可使用此功能。基本的故障是您将电子邮件和密码发布到代理OAuth2服务器请求的路由。您将中继身份验证并将令牌刷新回给用户,然后用户可以使用Authorization: Bearer LongEncryptedTokenHere...标头将访问令牌附加到每个后续请求。

为了简化操作,Laravel提供了CreateFreshApiTokens中间件,它将自动授权并刷新每个请求的令牌。您可以阅读Consuming Your API With JavaScript here

使用password授权和Guzzle请求令牌的示例:

$http = new GuzzleHttp\Client;

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'username' => 'taylor@laravel.com',
        'password' => 'my-password',
        'scope' => '',
    ],
]);

return json_decode((string) $response->getBody(), true);

来自Password Grant Tokens

答案 1 :(得分:0)

尝试将会话作为中间件单独添加到$ middlewareGroups。

它应该包含 \ Illuminate \ Session \ Middleware \ StartSession :: class,

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

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

        'sessions' => [
            \Illuminate\Session\Middleware\StartSession::class,
        ]
    ];

路由/ api.php

Route::group(['middleware' => ['sessions']], function () {
    Route::resource(...);
});