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.
Related
I'm working with laravel, using Cors and passport. Everything works great but authentication with the route ({{HOST/oauth/token}}) is not working always get
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"
every other route is working perfectly. SO I just need to tell passport to use cors, I have tried this
In AuthServiceProvider
Passport::routes(null, ['middleware' => [\Barryvdh\Cors\HandleCors::class]]);
and this
Route::group(['middelware' => 'cors'], function () {
Passport::routes();
});
but nothing, login with oauth no working at all. Thank you in advance!!!
change the middleware statement to
Passport::routes(null, ['middleware' => [ \Barryvdh\Cors\HandleCors::class ]]);
refer to https://github.com/barryvdh/laravel-cors/issues/243
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'
]);
});
I'm using this route in a project hosted in my local mac pc, it is working, but when i have uploaded that to an Ubunto server route conflict occurred.
Route::group(['prefix'=>'report', 'middleware' => ['auth','session', 'complete_profile']], function() {
Route::get('/get_query', 'ReportController#get_queries');
});
Route::group(['middleware' => ['auth','session', 'complete_profile']], function(){
Route::resource('report','ReportController');
});
for example when i use form first route report/get_query in online ubunto server it goes to the show($id) method of that controller, But in local its working.
What should I do with this ?
Route::group(['prefix'=>'report', 'middleware' => ['auth','session', 'complete_profile']], function() {
Route::resource('/','ReportController',['except' => ['show']]);
Route::get('/get_query', 'ReportController#get_queries');
});
Resource route has predefined route for http methodes. For example reporte resource has route:
Route::get('report/{report}','ReportController#show');
Solution is to exclude some methodes (routes from restfull resource), or to make some routes that wont conflict with route resource.
You can see what route you have registered by running:
php artisan route:list
Also one route group for report is enough just put '/' in resource route.
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.
I'm up and running with Laravel Spark, but I'd like to pull some of the user auth methods (and later, some others) in to my API.
Spark's default registration method is a POST request to /register that calls Auth\RegisterController#register.
I would like registration to be POST request to api/v1/register but for the sake of simplicity, I'd like to simply call Spark's Auth\RegisterController#register method.
I did try simply copying the RegisterController from Spark in to my app's controller directory, but that didn't seem like an elegant solution and it didn't work anyway.
My app\Http\api.php contains the following group:
Route::group([
'prefix' => 'api/v1',
'middleware' => 'auth:api'
], function () {
Route::get('register', 'Auth\RegisterController#showRegistrationForm');
Route::post('register', 'Auth\RegisterController#register');
});
I'd love input and advice on the best way to pull in some of those Spark methods that I get out of the box.
Thanks in advance!