Я создал Аутентификацию API с использованием паспорта laravel. При неправильном использовании токена авторизации выдается сообщение об ошибке «Маршрут [логин] не определен» - PullRequest
3 голосов
/ 12 марта 2019

Я создал API-аутентификацию с использованием паспорта laravel. Когда токен авторизации ошибается, он отправляет мне сообщение об ошибке «Маршрут [логин] не определен», хотя мне нужен JSON-ответ, например «unauthorized 401»

Это api.php Здесь users/authenticate - это маршрут входа в систему, но когда я использую другие маршруты, которые находятся в промежуточном программном обеспечении auth:api. Если токен будет неправильным, отправьте мне сообщение об ошибке «Route [login] не определено», но эта ошибка мне не нужна. Мне нужна ошибка JSON, такая как {error: unauthorized, code: 401}.

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
    Route::post('users/authenticate', ['uses' => 'Auth\LoginController@login']);






Route::group(['middleware' => ['auth:api']], function() {    
    /* Business details for New register business, get all business, update business, get single business */
    Route::post('businesses/create', ['uses' => 'Business\BusinessController@businessRegister']);
    Route::post('businesses/{id}', ['uses' => 'Business\BusinessController@businessUpdate']);
    Route::get('businesses/{id}', ['uses' => 'Business\BusinessController@businessGet']);
    Route::get('businesses-info/{id}', ['uses' => 'Business\BusinessController@businessInfoGet']);

});

это auth.php

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

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Это AuthServiceProvider.php

<?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
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}

Это app.php

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        Laravel\Passport\PassportServiceProvider::class,

    ],

Это Handler.php

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }


}

Ответы [ 2 ]

2 голосов
/ 12 марта 2019

Я столкнулся с той же проблемой, затем добавил Auth::routes(); в конце web.php, после чего он начал работать.

Я не знаю, правильно это или нет, но это решило проблему.

Другая причина может заключаться в том, что вы не отправляете заголовки, необходимые для laravel, т.е.

'accept' => 'application/json', //it tells server to send only json response
'content-type' => 'application/json'   // it tells front-end app to send data in json format

Надеюсь, что это может решить вашу проблему

1 голос
/ 12 марта 2019

Вам необходимо настроить свой код и добавить следующий код в код:

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
           ? response()->json(['message' => 'Unauthenticated.'], 401)
           : redirect()->guest(route('users/authenticate'));
}

Это будет работать для вас

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...