Laravel 5.4 : Api route list - php

I have the following lines in my routes/api.php
Route::middleware('api')->get('/posts', function (Request $request) {
Route::resource('posts','ApiControllers\PostsApiController');
});
When I hit http://localhost:8000/api/posts it comes back blank, but when I move the above route to routes/web.php like so:
Route::group(['prefix' => 'api/v1'],function(){
Route::resource('posts','ApiControllers\PostsApiController');
});
it works.
As a reminder I have cleared the routes cache file with php artisan route:clear and my route list comes with php artisan route:list when my routes/web.php is empty and routes/api.php has the above route:
Domain
Method
URI
Name
Action
Middleware
GET|HEAD
api/posts
Closure
api
Note that with web routes part the list comes ok and works fine.
What am I doing wrong here?

Dont use the middleware api and see following route example for API routes
Example 1 (in your api.php)
Route::get('test',function(){
return response([1,2,3,4],200);
});
visit this route as
localhost/api/test
Example 2 (if you want api authentication, token based auth using laravel passport)
Route::get('user', function (Request $request) {
///// controller
})->middleware('auth:api');
You can make get request for this route but you need to pass the access token because auth:api middleware has been used.
Note: see /app/http/kernel.php
and you can find the
protected $routeMiddleware = [
//available route middlewares
]
There must not be such (api) kind of middle ware in this file (kernel.php) for routes unless you create one, that why you can not use middleware as api.
Here, How I am creating REST APIs (api.php)
//All routes goes outside of this route group which does not require authentication
Route::get('test',function(){
return response([1,2,3,4],200);
});
//following Which require authentication ................
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
Route::get('user-list',"Api\ApiController#getUserList");
Route::post('send-fax', [
'uses'=>'api\ApiController#sendFax',
'as'=>'send-fax'
]);
Route::post('user/change-password', [
'uses'=>'api\ApiController#changePassword',
'as'=>'user/change-password'
]);
});

Related

Auth or auth-api middleware in api routes in laravel

For apis auth I am currently using:
Route::group([
'middleware' => 'auth:api'
], function() {
Route::post('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
If I want to use same for session based logins do I need to create same routes in web.php file or can I set up middleware in AuthController constructor with something like this or this?
In this answer 'auth:api' means auth is checking for api so do I need to pass anything there to check for sessions like 'auth:api,web' or what?
Create same routes in web.php just ommit the middleware, as web middleware is applied automatically. Same goes for api.php, auth:api is default middleware there.

Passport authentication is not working in laravel 5.3

I have set-up Laravel using passport as per the documentation here:
https://laravel.com/docs/5.3/passport.
I have written one route in API route and send request http://localhost/laravel_project/public/api/user using postman but its showing me below error:
NotFoundHttpException in RouteCollection.php line 161:
I have the following route (in routes/api.php):
Route::get('/user', function (Request $request) {
return array(
1 => "John",
2 => "Mary",
3 => "Steven"
);
})->middleware('auth:api');
but when I removed ->middleware('auth:api') line in the route it's working fine for me.
How can I fix this?
Also please tell me if I don't want to add passport authentication in my some routes how can i do this?
I was having the same problem, it seems you have to specify the Accept header to application/json as shown by Matt Stauffer here
Some further notes:
Your default Accept header is set to text/html, therefore Laravel will try redirect you to the url /login but probably you haven't done PHP artisan make:auth so it wont find the login route.
When you remove the middleware it will work because you are no longer authenticating your request
To authenticate some routes, just group them using Route::group and auth:api as the middleware
In your routes/api.php you can do this:
Route::group(['middleware' => 'auth:api'], function(){
Route::get('/user', function (Request $request) {
return array(
1 => "John",
2 => "Mary",
3 => "Steven"
);
});
});
All the routes you define inside this group will have the auth:api middleware, so it will need passport authentication in order to access to it.
Outside of this group you can put your api routes that doesn't need authentication.
EDIT: In order to make sure that the route actually exists with the required middleware, run php artisan route:list.

Laravel 5.3 API

When user enter username and password on the the browser and successfully logged in.
I like to make some API requests after user have logged in.
Laravel 5.3 provide api.php in routes folder.
in api.php I have included:
Route::group(['middleware' => ['auth']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
When requesting domain.com/api/test on the browser, for some reason it is redirecting to /home?
API token is not needed.
If you are specifying routes in api.php, you will need to use the auth:api middleware. So using your example it would be:
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
Notes about Token auth and Laravel 5.3:
If you've setup laravel's default auth system, you will also need to add a column for api_token to the user table. If you are using DB seeders, you might want to add something like:
$table->char('api_token', 60)->nullable();
to your users table seeder. Alternatively just add the column manually and fill that column with a random 60-char key.
When making the request, you can add the api_token as a URL/Querystring parameter like so:
domain.com/api/test?api_token=[your 60 char key].
You can also send the key as a header (if using Postman or similar), i.e:
Header: Authorization, Value: Bearer [your 60 char key].
I order to get a useful error if the token is incorrect, and not just be redirected to login, also send the following header with all requests:
Header: Accept, Value: application/json. This allows the expectsJson() check in the unauthenticated() function inside App/Exceptions/Handler.php to work correctly.
I found it hard to find clear docs from Laravel about using token auth with 5.3, I think it's because there's a drive to make use of Passport, and it supports tokens in a different way. Here's the article that probably helped most getting it working: https://gistlog.co/JacobBennett/090369fbab0b31130b51
first install the passport as stated here laravel passport installation
while consuming your own api add below line in your config/app.php in middleware section
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
now change your route to
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
now in your config/auth.php change these lines
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
The reason you are being redirected back to home is because the auth middleware checks if a user session is stored in your browser, but since api middleware does not make use of sessions (see app\http\kernel.php), your request is considered unauthenticated
If you would like to perform simple APIs that utilize sessions, feel free to add them in your web routes, and make sure to secure them by grouping them inside an auth middleware.
The standard behaviour in Laravel 5.5 is to delegate handling of authentication exceptions to app/Handler::unauthenticated(), in your project's application code. You'll find the code in there that redirects to the login page, and you can override it or perform further tests and contextualization in there. In previous versions of Laravel, 5.3 among them I believe, this exception handling was executed way down within the Laravel library within the vendor folder.

How to use middleware in Laravel for secure controllers?

I need to configure middleware in Laravel that all controllers will be secured by Auth.
I mean that will redirection for every incoming request if user is not authorized.
You can do the following in your routes file:
Route::group(['prefix' => 'admin'], function () {
Route::group(['middleware' => ['auth'], function() {
...Your routes here
This will apply the auth middleware to all routes prefixed with admin. You can of course also leave the prefix away if you don't need it.

Laravel 5.2 Auth not Working

As you guys know Laravel 5.2 was released a few days ago. I am trying this new version. I made a new project using the following command on CLI:
laravel new testapp
As per documentation of Authentication Quickstart, I followed the following command to scaffold routes and views of authentication:
php artisan make:auth
It worked fine. Registration is working fine. But I am facing problem in Login. After login I tested following in route.php file:
Route::get('/', function () {
dd( Auth::user());
return view('welcome');
});
Auth::user() is returning null and also Auth::check() and Auth::guest() are not working appropriately. I have tried same thing again and again two three times by making new projects but couldn't get the correct results.
Below is the complete route.php
<?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
dd( Auth::());
return view('welcome');
});
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
//
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});
Can anyone help me? or Is anyone facing the same problem? How can I fix it?
Laravel 5.2 introduces the middleware groups concept: you can specify that one or more middleware belongs to a group, and you can apply a middleware group to one or more routes
By default Laravel 5.2 defines a group named web, used to group the middleware handling session and other http utilities:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
So, if you want session handling, you should use this middleware group for all the routes in which you want to use authentication:
Route::group( [ 'middleware' => ['web'] ], function ()
{
//this route will use the middleware of the 'web' group, so session and auth will work here
Route::get('/', function () {
dd( Auth::user() );
});
});
UPDATE FOR LARAVEL VERSION >= 5.2.27
As of Laravel 5.2.27 version, all the routes defined in routes.php are using by default the web middleware group. That is achieved in app/Providers/RouteServiceProvider.php :
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web'
], function ($router) {
require app_path('Http/routes.php');
});
}
So you don't need anymore to add manually the web middleware group to your routes.
Anyhow, if you want to use the default authentication for a route, you still need bind the auth middleware to the route

Categories