9

I want to make authentication for API requests coming from mobile users.

I followed this and made api_key column inside users table.

I also created middleware:

public function handle($request, Closure $next)
{
  $token = $request->bearerToken();
  return $next($token);
}

What I want is to get bearer token from header and check it against user table.

How to achieve this?

2 Answers 2

10

Append the auth:api middleware to any route or group of routes and the Bearer token will be checked automatically for you without a custom middleware

Route::get('url', 'controller@method')->middleware('auth:api');

But to answer the question, here's what you can do (still not recommended but works)

<?php

namespace App\Http\Middleware;

use Closure;

class ApiAuthentication
{
    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken();
        $user = \App\User::where('api_token', $token)->first();
        if ($user) {
            auth()->login($user);
            return $next($request);
        }
        return response([
            'message' => 'Unauthenticated'
        ], 403);
    }
}

Register the middleware in App\Http\Kernel

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    // Here for example
    'custom_auth' => \App\Http\Middleware\ApiAuthentication::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

And protect a route with that middleware name

Route::get('/', function () {
    // Return authenticated user model object serialized to json
    return auth()->user();
})->middleware('custom_auth');

Result

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

this worked, can you explain why it's not recommended?
Because your mobile users aren't supposed to send a weird looking api token, they expect a username and password
2

I would recommend laravel/passport as it is much secure and easier. Click Here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.