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.
Related
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 want only my payment checkout pages in https. I have a website in http://, I´m implement a payment checkout with Stripe credit card, but Stripe only works with https...
I want that all my website have http, except the /payment-date page and the payment-data-post page, to send the data to Stripe with secure protocol.
How I can have only those two pages on https?
The routes are:
Route::get('/payment-data',['as'=> 'payment_data','uses' => 'WebController#getPaymentData']);
Route::post('/post-payment-data', ['as' => 'post_payment_data', 'uses' => 'WebController#postPaymentData']);
I want only this routes in https
The framework is Laravel 5.3
I think a good practice would be to create a Middleware which you then can use on whatever routes you'd like.
Using your Terminal, navigate to your project’s root directory and issue the following artisan command (to create ForceHttpProtocol middleware):
php artisan make:middleware ForceHttpProtocol
Change the newly created /app/Http/Middleware/ForceHttpProtocol.php so it looks something like this (will work only on production):
<?php
namespace App\Http\Middleware;
use Closure;
class ForceHttpProtocol {
public function handle($request, Closure $next) {
if (!$request->secure() && env('APP_ENV') === 'pro') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Next step is to update /app/Http/Kernel.php by adding the 'App\Http\Middleware\ForceHttpProtocol' which will make Laravel aware of your custom middleware.
If you want to apply middleware only on specific routes, you just have to assign middleware to routes by adding 'App\Http\Middleware\ForceHttpProtocol' instruction to $routeMiddleware array.
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
...
'forceSSL' => App\Http\Middleware\ForceHttpProtocol::class,
];
Just use the newly created middleware as you’re used to:
Route::get('payment-date', ['middleware' => 'forceSSL', function()
{
// do stuff
}]);
That should be it!
You can specify if routes should be HTTP or HTTPS by passing ['http' => true] or ['https' => true] as options when declaring your routes, if you don't specify those options then it should just use the same protocol as you're currently accessing the page with.
Route::post('/form', ['uses' => 'FormController#postForm', 'https' => true]);
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.
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!
I'm using the tymon/jwt-auth package for authentication an api with Laravel. It's working quite well and I have everything working properly.
However I'm unsure how to setup the jwt.refresh token middleware. I'm under the assumption that it will "auto-refresh" the token when expired?
I've add both to my middleware but can't seem to make it work.
Route::group([
'prefix' => 'api/v1',
'namespace' => 'Api\v1',
'middleware' => ['jwt.auth', 'jwt.refresh']
], function ($app) {
// Routes here
});
Perhaps I'm not sure how it works exactly, do I need to do polling for a some refresh end point. I kind of thought that was what the middleware was supposed to do automatically per request?
If you use the jwt.refresh middleware, the token is refreshed on every request. It's returned as a header on the response, so you need to take that header and store the new token on every request.
The returned Authorization header will be of the form Token: xxxxxxxxx