hellicious's avatar

securing API in lumen

im new in lumen and i want to securing my registration so only people that know the code/api token can register a new user but everytime i try to input the code in postman i cant register a user

here is what ive done so far

AuthServiceProvider

<?php

namespace App\Providers;

use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            $header = $request->header('Api-Token');

            if ($header && $header == 'bird') {
                return new User();
            }

            return null;
        });
    }
}

Routes

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$app->get('/', function () use ($app) {
  $res['success'] = true;
  $res['result'] = "Hello there welcome to web api using lumen tutorial!";
  return response($res);
});

$app->post('/login', 'LoginController@index');
$app->post('/register', ['middleware' => 'auth', 'uses' => 'UserController@register']);
$app->get('/user/{id}', ['middleware' => 'auth', 'uses' =>  'UserController@get_user']);

UserController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Auth;

class UserController extends Controller
{
    /**
     * Register new user
     *
     * @param $request Request
     */
    public function register(Request $request)
    {
        $hasher = app()->make('hash');
        $username = $request->input('username');
        $email = $request->input('email');
        $password = $hasher->make($request->input('password'));
        $register = User::create([
            'username'=> $username,
            'email'=> $email,
            'password'=> $password,
        ]);
        if ($register) {
            $res['success'] = true;
            $res['message'] = 'Success register!';
            return response($res);
        }
        else{
            $res['success'] = false;
            $res['message'] = 'Failed to register!';
            return response($res);
        }
    }
    /**
     * Get user by id
     *
     * URL /user/{id}
     */
    public function get_user(Request $request, $id)
    {
        $user = User::where('id', $id)->get();
        if ($user) {
              $res['success'] = true;
              $res['message'] = $user;
        
              return response($res);
        }
        else{
          $res['success'] = false;
          $res['message'] = 'Cannot find user!';
        
          return response($res);
        }
    }
}

so what did i do wrong ? thanks in advance

0 likes
2 replies
Robstar's avatar

What happens exactly? Did you note any errors in the log and/or on screen?

Some observations:

  • I always prefer to return a valid user instance from the auth service provider, based upon the token i.e:
public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            $token= $request->header('Api-Token');

           User::query()
                    ->whereApiToken($token)
                    ->first(); 
        });
    }

That method can be found at https://github.com/laravel/lumen/blob/master/app/Providers/AuthServiceProvider.php#L33

Also, are you passing the token via Postman as a proper header, as opposed to via the query string? Try hard coding in a valid api token in your service provider - does registration work now?

I'm guessing a little here as you have particularly provided much for me to go on :)

hellicious's avatar

i was trying to secure my registration with password or something like that and ive already done it with JWT :)

Please or to participate in this conversation.