3

I am trying to create a Laravel API project. So I have this project with basic laravel's scaffolding set up. In my user migration I have added:

$table->string('api_token', 60)->unique();

then in my User.php model i have added:

 protected $fillable = [
    'name', 'email', 'password','api_token'
];

Then in my api.php i have made a test route:

Route::group(['middleware' => ['auth:api']], function(){

Route::get('/test', 'ApiController@test');

});

in my Apicontroller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ApiController extends Controller
{


public function test(Request $request){

return response()->json(['name' => 'test']);


}



}

so now i type this : with my api_token

localhost/project1/public/api/test?api_token='hsvdvhvsjhvasdvas8871238'

It's not giving me the json data, instead it's redirecting to the logged in home page

3
  • try localhost/project1/test? Commented Mar 3, 2017 at 2:51
  • thx SteD for the reply..i fixed it. its a silly mistake i made. didn't include the /api in the route. but now i have another problem please see my edited question. Commented Mar 3, 2017 at 2:57
  • 1
    @SteD sorry, its silly mistakes again. i fixed it :) sorry again my bad should have been a little more patient lol. Commented Mar 3, 2017 at 3:06

3 Answers 3

2

localhost/project1/public/index.php/api/test?api_token='hsvdvhvsjhvasdvas8871238' would help.

If you want pretty urls, read the documentation: Pretty URLs

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

1 Comment

It's not a safe practice to send the token via GET params.
1

For laravel 5.2
Middleware/ApiAuthenticate

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class ApiAuthenticate
{

    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            return response()->json(['status'=>'error','message'=>'token mismatch']);;
        }
        return $next($request);
    }
}


Kernel.php add

protected $routeMiddleware = [
    'autho'      => \App\Http\Middleware\ApiAuthenticate::class,
];


routes.php

    Route::group(['prefix'=>'api','middleware'=>'autho:api'], function(){
        Route::get('aaa','Api\AAAController@index');
    });

Comments

0

You would not have to write your own API middleware and routes if you use Laravel 5.3 or higher version.

Moreover, you can use the in-built Passport package to manage the access token, using oAuth2.

$http = new GuzzleHttp\Client;

$response = $http->post($apiUrl.'oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => '2', //this can be generated when you setup Passport package or using artisan commands
        'client_secret' => 'xxxxxxxxx', //this can be generated when you setup Passport package or using artisan commands
        'username' => '[email protected]',
        'password' => 'test123',
        'scope' => '',
    ],
]);

$responseData = json_decode($response->getBody(), true);

$token = $responseData['access_token']; //Now I have the token so I can call any protected routes 

$response = $http->request('GET', $apiUrl.'api/v1/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$token,
    ],
]);

$responseData = json_decode($response->getBody(), true);
echo "Name of the user is: ".$responseData['name'];

2 Comments

Thx tanay jha for the reply. I tried following the passport documentation. but it's kinda hard , cuz it's talking about vue.js and gulp front end stuffs. which is pretty confusing.
@MohamedManas you don't really need to use Vue.js, that is only required if you want your frontend to be Vue.js based. See my edited answer.

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.