A
A
Allexon2017-05-17 17:10:25
API
Allexon, 2017-05-17 17:10:25

How to make authorization/authentication for API by token in Laravel?

Laravel 5.3
We need to make an API for an application in which regular authorization is implemented by standard Laravel tools, everything is standard:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],
'users' => [
            'driver' => 'database',
            'table' => 'users',
 ],

I created a controller for the API, with a method that receives a login and password, authorizes the user and returns a remeber_token to the application.
After that, this remeber_token will be passed by the mobile application with each request to the methods inside the construct:
Route::group(['middleware' => ['auth:api']], function() {
// роуты
});

and everything will be fine, I thought...
But it didn't work. For requests to private routes, I get a redirect to the authorization form (although this behavior should only be when working through a browser, but not for api routes).
What is done wrong? How do guards work? How should the framework find out in which field the token was passed and with which field in the database it should be compared? Is it implemented out of the box in the same way as regular authorization/authentication?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andy Developer, 2017-05-17
@UmbrellaCoders

look at https://github.com/tymondesigns/jwt-auth

A
Artyom Prosvetov, 2017-05-17
@Dragomeat

Slightly off topic, but maybe you should look at laravel/passport?

A
Alex Wells, 2017-05-17
@Alex_Wells

And why JWT? Headers:
1. jwt: "Authorization: Bearer lotsOfSymbolsHere"
2. cookies: "Set-Cookie: laravel_session=123; token=456"
Now explain why you bother with absolutely useless technology? Which, moreover, will require so much manipulation, and even worse than cookies?
Read on the Internet why you should NOT use JWT. Yes, you may have already written everything for jwt, but at least it will be for the future)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question