
At the end of last summer, I thought about a simple way to authorize forum users in a mobile application. Just at that time, the
Laravel 5.3 version came out along with the
Laravel Passport package, where this was offered out of the box. Previously, I did not work with
OAuth 2 , so I began to slowly understand. I decided to try the mechanism on rats, in a small game on
Unity about the Rat on the Wall. The game itself is the simplest runner, but the authorization mechanism may be of some interest if you have not previously encountered this. I used the
official documentation and the
Passport article . On Habré a suitable article has not yet appeared, so I decided to compile the material myself, implementing for the interest of adding records and basic interaction with the client on
Unity . In view of my leisureliness, this stretched out for almost a year, so now
Laravel 5.5 and
Unity 2017.1 are used in the examples.
In the first part of the article we will understand how to add a user record to the site using an authorization token.
NoteImmediately I would like to note that I am considering a fairly simplified implementation - in a real project it would be worth using the validation of records, highlight the processing of requests into a separate controller, and not write directly in the route, encrypt the token while saving in Unity, and another such plan - the article sets goals to cover all such moments, so they were omitted by me. I consider it step by step, for beginners, but still I assume that the reader has basic skills in working with a local server and Unity. If something is too detailed or not detailed - write in the comments! This is my first technical article and I am open to suggestions.
Installing Laravel and Laravel Passport
- Create a new project Laravel , start a database for it.
- Install the Globally Auxiliary Laravel Installer via the console using Composer
')
composer global require "laravel/installer"
- To create a project through the installer, just type a command in the
laravel new < >
format of laravel new < >
laravel new ratwall-laravel
Further commands are executed from the created directory. We go there
cd ratwall-laravel
- In the
.env
file .env
write the data to connect to the database. In this guide we will work with SQLite, we will prescribe
DB_CONNECTION=sqlite DB_DATABASE=//////database/database.sqlite
After that, create the corresponding empty file (using the touch database/database.sqlite
command from the console or, in the case of Windows, from any editor, the database.sqlite
file in the database.sqlite
directory) - Now you can run the project locally with the command
php artisan serve
It will be available at http://127.0.0.1:8000/
- For our project, the basic authentication system on the site will suffice, so we run the command
php artisan make:auth
- Add Laravel Passport dependencies through omposer .
composer require laravel/passport
For Laravel versions below 5.5For versions of
Laravel below
5.5 in the
config/app.php
it was necessary to register the corresponding service provider. To do this, add the string to the
providers
array
Laravel\Passport\PassportServiceProvider::class,
If you install
Laravel 5.5 (current at the time of publication of the article) or higher - this item can be skipped.
- The basic authentication system has created its own migrations. Import to database along with Passport migrations.
php artisan migrate
- Now you can run the Passport installer.
php artisan passport:install
The installer will create a pair of keys, in the future we will work with a key like Password grant client , so you can immediately write the key for Client ID = 2 .
- Add the
Laravel\Passport\HasApiTokens
with the Passport methods to the App\User
model. The class will look like this:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use Notifiable, HasApiTokens;
- The next step is to assign routes. Here it is done by adding the
Passport::routes
method to the service provider’s boot method
App\Providers\AuthServiceProvider
. The service provider will look like this:
<?php namespace App\Providers; use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Laravel\Passport\Passport; class AuthServiceProvider extends ServiceProvider {
- Finally, in the
config/auth.php
install the driver at the api
config/auth.php
as a passport
.
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
Password grant token
There are several ways to authenticate with Passport . We will consider the simplest method of authorization through login-password, through Password Grant Token . This method allows the user to fill in the authorization form directly in your application. When installing Laravel Passport, one client for this authentication method has already been created ( Password grand client , Client ID = 2 ), you can use it. To create a new need to run
php artisan passport:client --password
Enter a name for the client to complete the creation. The command displays Client ID and Client Secret . Remember them, they will be needed in this article, and in the next, when forming a request from the client of the game.
Model Records
Create a model for future records. The -m
switch means that the corresponding migration will also be created. Adding the -c
will also create a controller, but in our simplified case, this is not necessary.
php artisan make:model Record -m
After creating the model, you need to prepare the migration. Edit the database/migrations/<>_create_records_table.php
. By default, the migration has the creation of the id
field (for the primary key) and two fields for saving the time for creating and editing the record ( timestaps
). For the simplest storage of data on records, we add two numeric fields — the score
(the value of the record) and user_id
(the identifier of the user who set the record). After that, the migration will look like this:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRecordsTable extends Migration { public function up() { Schema::create('records', function (Blueprint $table) { $table->increments('id');
Import to DB with the command
php artisan migrate
Edit the App\Record
model itself. Add the user()
method to communicate with the user model in the user_id
field.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Record extends Model {
Controller of records
To add a record to the database, create two routes for the API, which are almost the same, but one of them is designed to add a record to an anonymous user, and the other is authorized. In this tutorial, we will not write a separate controller for records, we will move all processing to an anonymous function of the route. To do this, in the routes/api.php
we add:
Route::post('/anonymrecord', function (Request $request) {
Here we pass the record in the POST request, add it to the database and return the message of success. We added two almost identical routes - the first for an anonymous add, the second for a record by an authorized user. An authorized user can use an anonymous route, but the user information will not be processed correctly in it, so we divided the routes as a solution. When the second route is called by an anonymous user, you will be redirected to the authorization form.
There was already one user
route in this file to get information about the authorized user. We will return to it later.
You can test the request for adding an anonymous record using the Postman -type http client (hereinafter referred to as examples with it) by sending a POST request with the specified numerical score value in the form at http://127.0.0.1:8000/api/anonymrecord . In response, we will get json
with the message that the record has been added.

NoteWe add the record as it is, meaning that the score field is integer and non-negative. I think it’s not worthwhile to dwell on the fact that in a real project this should be checked, especially since in Laravel this could be done in a special query class for the same record. In addition, it would be worthwhile to add the controller to the class (if necessary, highlighting the entry in a separate repository class) to get rid of code duplication.
To display the added records on the site, write a route in routes/web.php
requesting all the records from the database. It uses the records.blade.php
template, which we will create in the next step.
Route::get('/records', function () { $records = \App\Record::all(); return view('records', compact('records')); });
Presentation of records
Create a template resources/views/records.blade.php
to display a high score table.
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading"></div> <div class="panel-body"> <table class="table table-striped table-hover"> <tr> <th></th> <th></th> <th></th> </tr> @foreach ($records as $record) <tr> <td>{{ $record->user ? $record->user->name : '' }}</td> <td>{{ $record->score }}</td> <td>{{ $record->created_at->diffForHumans() }}</td> </tr> @endforeach </table> </div> </div> </div> </div> </div> @endsection
If the record is added by an authorized user, we display its name, otherwise - Anonymous .
Now, at http://127.0.0.1:8000/records, we have a table of records available to us - empty or with the records we added via Postman .

These records were added from Anonymous , because we referred to the anonymous add route, and not to the authorized user route with the authorization token via Postman . Let's deal with the second case.
Authorization through OAuth 2
Register on the site using the standard Laravel mechanism by going to http://127.0.0.1:8000/register . For example, I have specified e-mail habr@habrahabr.ru , password habrahabr , name Habr .
In order to get an authorization token via Password Grant Token , you need to send a POST request to the address http://127.0.0.1:8000/oauth/token . The following data should be added to the request body:
grant_type
- specify the type of password , because we use Password Grant Token ;client_id
- Client ID from Password Grant Token ;client_secret
is the Client Secret key from the Password Grant Token section;username
- e-mail is used as the login for authorization in the basic Laravel functionality;password
- passwordscope
- token application areas (for setting permissions), leave * , i.e. everything.
Let's send such request through Postman . If everything is filled in correctly, in response we will receive an update token, an authorization token, a token validity time in seconds and the type of the token - Bearer . We need an authorization token - Access Token .

Check the token in action, having received information about the authorized user. Perform a GET request via Postman at http://127.0.0.1:8000/api/user . In this case, in the Headers section of the new request, you need to add an Authorization
key with the value Bearer < >
(that is, the type of token, the space, the token itself). As a result, we will receive information about the user to which this authorization token corresponds.

Add a record by an authorized user
Now you can perform a POST request for adding a record by an authorized user through Postman . Fill in the Headers of the new POST request in the same way as the last one; we use http://127.0.0.1:8000/api/record as the address. The reply message now displays the username that corresponds to the transmitted token.

If you go to the page of records, you can see that the last record added is the user name.

In the following part we will work with our small API already from Unity .
The finished project can be downloaded on githabe .