E
E
Eugene2018-02-10 13:47:14
API
Eugene, 2018-02-10 13:47:14

How to do authorization by token for API in Laravel?

I'm trying to use the existing authorization for the API by token out of the box. The process seems to have been studied and partially implemented. I set up authorization by token, hung on a group of routes:

Route::group(['middleware' => ['auth:api']], function() {
// тут прописал все свои маршруты
});

The problem is that if the token is not passed or it is incorrect, it does not return a 401 or 404 error code, it tries to redirect to authorization (login), although what kind of authorization or registration for the application API.
Tell me how to set it up correctly so that in the absence or non-matching of the token, just give a 404 page or some of your data?
And it is not clear where to redefine the name of the variable itself, so that it would not be "api_token"

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alex, 2018-02-10
@atachrus

In order not to reinvent the wheel, you can use the ready-made solution Artem0071 https://github.com/tymondesigns/jwt-auth

I
Igor Shcherbin, 2018-02-15
@ischerbin

In my latest project, I made it simple. When accessing the API, you must pass the token in the header, in the X-Auth-Token field. The implementation is simple. We write middleware:

<?php

namespace App\Http\Middleware;

use App\AuthToken;
use Closure;

class TokenAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $_auth_token = $request->header('X-Auth-Token', null);

        if ($_auth_token)
        {
            $_token = AuthToken::find($_auth_token);
            if (!$_token)
                abort('401', 'No such token. Request a new one.');
        }
        else
            abort('401', 'No auth token provided');

        return $next($request);
    }
}

Then in Kernel.php we connect:
And everything works. Obtaining a token is done via a POST request to /api/token. How to implement it and then store it is up to you.
Laravel version 5.4

A
Artem0071, 2018-02-10
@Artem0071

I also recently started studying the framework and ran into this problem
. In general, I don’t know how smart this solution is, but you can go to app/Exceptions/Handler.php
There, as I understand it, all errors are intercepted
. Unauthenticated is used for authorization, so you can do this :

/**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->is('api/*')) {
             // тут пишите что хотите вывести, например: 
             return response()->json(['error' => 'auth']);
        }

        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest(route('login'));
    }

The rest of the errors can be in render () according to the same scheme
. I got something like this
if ($request->is('api/*')) {

            if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
                return $this->setStatusCode(400)->renderOutput();

            if ($exception instanceof AuthorizationException)
                return $this->setStatusCode(403)->renderOutput();

            if ($exception instanceof ModelNotFoundException)
                return $this->setStatusCode(404)->renderOutput();

            if ($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException)
                return $this->setStatusCode(405)->renderOutput();

            if ($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException)
                return $this->setStatusCode(405)->renderOutput();

//            return $this->setData(['extension of' => get_class($exception)])->renderOutput();
        }

C
CrazyLostAngel, 2022-04-18
@CrazyLostAngel

The logic for this behavior is in \App\Http\Middleware\Authenticate:

protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }

apparently in the API request you did not indicate that you were expecting JSON, which is why it redirects to the login page.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question