Laravel 5.3 护照 JWT 认证

Laravel 5.3 Passport JWT Authentication

早些时候,当我使用 laravel 5.2 时,我使用了第三方包 https://github.com/tymondesigns/jwt-auth/ 来进行基于 JWT 的身份验证。我们只需传递用户名和密码即可获得令牌。

现在 laravel 5.3 随着护照的引入,我想进行基于 JWT 的身份验证,但护照要求我指定 client_id 和 client_secret 以及用户名和密码。 tymondesigns/jwt-auth.

中没有

如果我在没有 client_id 的情况下发出请求,则会抛出错误 http://pix.toile-libre.org/upload/original/1482908288.png but when I pass the client_id and client_secret then it works fine http://pix.toile-libre.org/upload/original/1482908143.png

如何在 laravel 5.3 和 passport 中仅使用用户名和密码而不指定 client_id 和 client_secret.

发出 JWT 请求

所以,我终于要回答我自己的问题了。希望这对面临类似问题的人有所帮助。

JWT认证可以使用Laravel 5.3 passport完成,只需按照以下步骤操作:

或按照以下步骤操作:

  • 作曲家要求 laravel/passport
  • Laravel\Passport\PassportServiceProvider::class, 添加到您的应用提供商
  • php artisan 迁移
  • php artisan passport:install
  • 向您的用户模型添加 HasApiTokens 特征
  • 护照::路线();在 AppServiceProvider
  • 配置 api driver 到 passport

完成后,创建一个 UserController 并在其中添加以下方法:

public function auth(Request $request)
{

  $params = $request->only('email', 'password');

  $username = $params['email'];
  $password = $params['password'];

  if(\Auth::attempt(['email' => $username, 'password' => $password])){
    return \Auth::user()->createToken('my_user', []);
  }

  return response()->json(['error' => 'Invalid username or Password']);
}

  public function index(Request $request)
  {
    return $request->user();
  }

在routes/api.php中添加如下路由:

Route::post('auth', 'UserController@auth');

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

  Route::resource('user', 'UserController@index');

});

现在使用屏幕截图中显示的电子邮件地址和密码向 http://localhost:8000/auth 发出 POST 请求 (http://pix.toile-libre.org/upload/original/1483094937.png) 这将为您提供 accessToken,您可以使用此令牌在您的应用程序中通过 Authorization header 和 Bearer XXX 发出其他请求,其中 xxx 是 accessToken您从 /api/auth 端点收到。

现在,使用 Authorization header 和令牌值向 /api/user 发出 GET 请求,这将 return 经过身份验证的用户的详细信息。 (例如:http://pix.toile-libre.org/upload/original/1483095018.png

我还在我的博客 http://chatterjee.pw/larvel-passport-jwt-authentication/

上发布了这些步骤

希望对您有所帮助!

如果你对 OAuth 和 Client 的东西不感兴趣,你可能想使用纯 JWT 身份验证,如果是这样,你可以查看这个包:

https://github.com/miladrahimi/larajwt

它声明了一个名为 "jwt" 的新身份验证驱动程序来保护您经过身份验证的路由,它提供了从您的用户生成 jwt 的服务,以及一些其他工具,例如注销、用户模型缓存、用于检查额外属性的过滤器用户等等。

$request->user();对我不起作用,因为中间件配置为网络,我也需要 + api。文档不清楚如何控制这两种情况。

我能够通过 get Auth Bearer + token 获取用户详细信息,并在 Laravel:

use Illuminate\Support\Facades\Auth;

Route::get('/user', function() {
   return Auth::guard('api')->user();
});

你搞混了。 Passport 非常适合类似 Facebook 的应用程序,您希望用户的客户端安全地验证您的 API。

如果您所做的只是构建一个休息 API 例如健康和健身应用程序,使用 Tyson JWT 包就足够了。这是因为你没有中间人。