Issue with POST requests with Laravel Sanctum and Postman - laravel

I have a problem with Sanctum and Postman that's related to this post: SPA Authentication Issues with Sanctum and Postman
I followed everything from the Laravel docs about Sanctum and configured it correctly. Then I followed this tutorial: https://blog.codecourse.com/laravel-sanctum-airlock-with-postman/
Everything is working except for POST requests. When I do login, it works. But then I have a collection without the pre-request Script and when I do a GET request to for example /user, it will return the logged in user.
But when I change the method to POST in Laravel and in Postman, I'll get a CSRF token mismatch error.
Does anybody knows what I have to do, to make POST requests working?
Route::middleware('auth:sanctum')->post('/user', function (Request $request) {
return $request->user();
});

I've been using sanctum in one of my e-commerce APIs and I've also followed the same tutorial you've linked in the question. It's hard to tell what's the actual problem in your case but it seems like that you're not sending the X-XSRF-TOKEN header in your POST requests.
The last paragraph in the above-mentioned tutorial, the writer shows how to hit the /logout route which is a POST route.

Remove this function in the controller
public function __construct()
{
$this->middleware('auth');
}
Or change it to
public function __construct()
{
$this->middleware('auth:sanctum');
}
Also, check your RouteServiceProvider and change your API route to
Route::prefix('api/v1')
->middleware('auth:sanctum')
->namespace($this->namespace)
->group(base_path('routes/api.php'));

csrf_token is used to validate forms having method POST in laravel and token is created dynamically,
two thing you can do
First thing if you are writing api's you need to use https://<base_url>/api
and routes in routes/api.php, there you donot need csrf_token but make sure to use proper api authentication
Second just disable csrf token for those routes until you are testing on postman, once you successfully tested enable again, its provide security
disable like this
<?php namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'submitMyForm/*',
];
}

Related

register a public api route in laravel nova without authentication

I am developing a card for Laravel nova.
As part of this, I want an API route that can be posted, but I don't want to have to authenticate against it.
I have registered my route in the card's api.php
Route::post('/endpoint/{id}', function (Request $request, $id) {)
This works if I call it with an already authenticated session.
But if I try to call it from postman I get
HTTP 419 Sorry, your session has expired. Please refresh and try again.
I can see that the card service provider is registering the route as so
Route::middleware(['nova'])
->prefix('nova-vendor/NovaPusherCard')
->group(__DIR__.'/../routes/api.php');
So I guess that Nova is putting some authenticated in front of the route.
Is there a way I can register the route without adding authentication?
ok so I worked it out.
I just needed to update the middleware to api instead of nova.

Laravel Passport + Ionic User Authentication issue

I have an application in Laravel running on a live server and I am trying to consume its API with an Ionic application using Passport for the user authentication and the retrieval of the access_token.
After I have successfully retrieved the access_token making a request to the url: https://my-app.com/oauth/token, I save the access_token and I make a simple GET request to get a "hello" message that uses the "auth:api" middleware.
This GET request, when done to the live server returns a 401 status code. On the other hand, when I follow the same steps but on the localhost then it works fine.
All these steps are done on the Ionic application as well as the Postman application. And both ways yield the same results.
I really don't know what could be wrong. I have followed instruction online and on the laravel documentation.
1) First check that you added the passport middleware into your app\Http\Kernel.php > $routeMiddleware array.
2) Then protect routes with this passport middleware in app\Providers\RouteServiceProvider.php, like:
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('client_credentials')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
For more detail, you can check this answer source.

How to make laravel passport auth redirect in json response?

I am trying to create API with laravel passport authentication now it is very easy to make API with laravel passport. I am using personal access token to create access token for API users. As my client and server are both one, but when token not provided in the API it redirect to login page create by laravel auth scaffold php artisan make:auth, I want to return json response with message "Token not provided."
https://laravel.com/docs/5.4/passport#personal-access-tokens
I am using auth:api in routes.
How to pass json response for API if token not provided?
I also encountered this same issue. To solve that redirection, you have to pass an extra parameter into the header of the request:
Accept application/json
Now, it will return JSON response instead of redirection to the login page.
So now with an invalid request, it will return JSON response like:
{"error":"Unauthenticated."}
But there is no easy way to customize the passport responses. I'm searching some standard way, but didn't get any yet.
I also encountered this same issue. To solve that redirection, you have to pass header of the request of json response. for that i made decision to make middleware as below
public function handle($request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
the above middleware will force the header to add json response, group the api collection as below
Route::group(['middleware' => 'json.response'], function () {
//your routes here
});

How to authenticate API requests in Laravel?

I am currently building some sort of posts based web application using Laravel 5(.4). I have decided to load asynchronously the comment section for each post(and refresh it periodically). After some research I have decided to write a small integrated REST API (using the api routes of Laravel) that should answer to the requests made through AJAX.
However, I am facing the problem if authenticating the incoming requests. Take for example a request to post some comment. How exactly would you recommend to do that?
If you are making AJAX requests from browser and you are signed in then you don't need to use Laravel Passport tokens.
You can define certain routes which will be using web,auth middleware on requests like webapi/comments/get like this.
Route::group(['middleware' => ['web','auth]], function () {
Route::get('webapi/comments/get', 'CommentsController#get');
}
And use Auth Facade as you do in web request i.e Auth::check(), Auth::user() etc. and return the data in JSON like this.
class CommentsController extends Controller
{
public function get(Request $request)
{
if($request->acceptsJson()){
$data = array();
// add data
return response()->json([
"data"=> $data,
"status" => true
]);
}else{
return abort(404);
}
}
}
You can also send Accept header in AJAX request as application/json and in controller check if request $request->acceptsJson() and make your decision to show content when url is loaded from browser address bar or requested as AJAX.
Laravel Passport token are useful where there is no session and cookies are managed.
hope this helps :)
"Passport includes an authentication guard that will validate access tokens on incoming requests. Once you have configured the api guard to use the passport driver, you only need to specify the auth:api middleware on any routes that require a valid access token" - from the Laraven Documentation.
Apparently I have to configure passport, and after that configure the auth:api middleware to use the passport driver. Correct me if I'm wrong, please :)

Blacklisting JWT tokens

For my API i'm using this package tymondesigns/jwt-auth with Laravel.
Security is very important! Tokens will be blacklisted after every request with a new token in the response. While doing some tests using both middlewares jwt.auth and jwt.refresh on the same route I get mixed results. Sometimes it works OK, sometimes I get a 401 unauthorized and have to login again.
I'm using the jtw.auth middleware so I can make use of Auth::user() in my app.
$api->group(['middleware' => ['jwt.auth', 'jwt.refresh']], function ($api)
{
// Protected routes here
});
Does someone have a working example for this?

Resources