これは先週のチュートリアルの続きです。
This is a continuation of last weeks tutorial.
始めましょう
コンポーザー経由でパスポートをインストールする
Install passport via composer
docker run --rm -v $(pwd):/app composer require laravel/passport
移行を実行してパスポートをインストールする
Run migrations and install passport
sudo docker-compose exec app-server php artisan migrate
sudo docker-compose exec app-server php artisan passport:install
これで、お気に入りのエディター(私の場合はPHPStorm)を使用してプロジェクトを開き、 User
モデルを編集してHasApiTokens
特性を追加できます。
We can now open the project using our favorite editor, in my case PHPStorm, and edit the User
model to add the HasApiTokens
trait.
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
config \ auth.php
でApi認証プロバイダーをパスポートに変更します
We change the Api Auth provider to passport in the config\auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
Graphqlを構成する
職人を使用して新しい突然変異を作成する
create a new mutation using artisan
php artisan lighthouse:mutation Login
mutations
フォルダー内で、Login.php
を開き、invoke
」関数のコンテンツを置き換えます
Inside the mutations
folder, open the Login.php
and replace the invoke
function content
if(Auth::attempt($args)){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return $success;
}
schema.graphql
のリストに新しく作成されたミューテーションを追加します
Add the newly created mutation in the list on the schema.graphql
type Mutation {
createUser(name: String!, email: String!, password: String!): User
Login(email: String!, password: String!): Token
}
type Token{
token:String!
}
新しい突然変異を使用してログインします
Make a login using the new mutation
mutation{
Login(email:"my@email.com",password:"mypassword"){
token
}
}
トークンをテストするには、 auth:api
ミドルウェアを追加して、schema.graphql
内のクエリの1つを変更します
To test the token, modify one of the queries inside the schema.graphql
, by adding the auth:api
middleware
type Query {
allusers: [User!]! @all
users: [User!]! @paginate(defaultCount: 10)
user(id: ID @eq): User @middleware(checks:["auth:api"]) @find
}
新しいクエリリクエストを行うときは、忘れずに認証ベアラートークンヘッダーを追加してください
When you make the new query request, remember to add the Auth Bearer token header
Authorization Bearer: eyaz.........
query{
user(id:1){
id,
name,
email
}
}