I try to use phpunit with Laravel and Spatie but i have a issue.
I have this test :
public function testBasicTest()
{
$user = User::where('id', 2)->first();
$response = $this->actingAs($user, 'api')->json('POST', '/providersList', [
'database' => 'test'
]);
$response->assertStatus(200);
}
But i have a 401 error
Expected status code 200 but received 401. Failed asserting that 200 is identical to 401.
I have this in web.php
Route::group(['middleware' => ['auth:api','role:Admin']], function() {
Route::post('/providersList', 'ProviderController#index');
});
This is a common issue when doing testing, I can assure you that the cause of this error is because of your authentication because of 401 HTTP error code, check if the acting user has role admin
To get a better error output, add this to the top of your test function
$this->withoutExceptionHandling();
It should give a better idea of what the issue is.
Related
My laravel project has an API route by auth.basic middleware which is used id of the authenticated user in the controller. when I call it in postman it works well and I get 401 when the username or password is incorrect, but in laravel APITest which extends from DuskTestCase, authentication does not take place so I get 500 instead of 401 when the user's informations were incorrect. However, by correct information, I have the same error because auth() is null.
it is written like below, which is wrong?
api.php route:
Route::get('/xxxxxx/xxxxxx/xxxxxxx', 'xxxxx#xxxx')->middleware('auth.basic');
APITest:
$response = $this->withHeaders(['Authorization' => 'Basic '. base64_encode("{$username}:{$password}")])->get("/xxxxxx/xxxxxx/xxxxxxx");
You can use actingAs() method for authentication in tests.
An example from docs:
public function testApplication()
{
$user = factory(App\User::class)->create();
$this->actingAs($user)
->withSession(['foo' => 'bar'])
->visit('/')
->see('Hello, '.$user->name);
}
Another example that you can use for an API:
$user = User::factory()->create();
$response = $this->actingAs($user)->json('GET', $this->uri);
$response->assertOk();
For more information: https://laravel.com/docs/5.1/testing#sessions-and-authentication
I'm gonna make a Unit Testing for my resource.
Here my testing function below :
public function testCreateMyResource()
{
$user = factory(\App\User::class)->states('admin')->create();
$this->actingAs($user);
$data = [
'Field' => "Example",
];
$response = $this->actingAs($user)->postJson('/nova-api/my-resource?editing=true&editMode=create',$data);
$response->assertStatus(201);
$response->assertJson(['status' => true]);
$response->assertJson(['message' => "Created!"]);
}
But it was return 403.
I expected to return 201 as I login normally to Nova dashboard and create new record in the form.
It seems like forbidden to access the route inside Testing Class.
Is there anyway to access the route ? Please any body help me to solve this.
Out the test it works, I can visit the page and the controller wroks fine. I wrote the following test:
public function test_logged_user_is_not_redirected()
{
PartnerFactory::new()->create();
$request = $this->actingAs(UserFactory::new()->create())
->get('partners')
->assertRedirect('partners');
dd($request->inertiaProps());
}
I get error code 500. This is the controller:
public function index()
{
return Inertia::render('Partners/Index', [
'filters' => \Illuminate\Support\Facades\Request::all($this->getFilters()),
'contacts' => function() {
return $this->getAllContacts();
}
]);
}
This is the route in web.php
Route::get('partners', [PartnersController::class, 'index'])
->name('partners')
->middleware('auth');
Using refresh database, tried url with a '/' before, I still get 500.
edit: without exception handling i get: Trying to get property 'id' of non-object
Found the solution: The user in jetstream MUST have the personal team!
I developed an API with Laravel 5.5. All is working fine.
But imagine that a user enter an "api" url directly in the browser (for example: api/books), then they will receive an error:
InvalidArgumentException
Route [login] not defined.
How to prevent this? I tried to add some routes in the routes/web.php file, but without success.
Or perhaps I should do nothing (there will be very few users who will do that)?
I found the answer here:
Laravel 5.5 change unauthenticated login redirect url
I only do that in the "app/Exceptions/Handler.php" file, I modified the function "render" like that :
public function render($request, Exception $exception)
{
// return parent::render($request, $exception);
// add dom
return redirect('/');
// or redirection with a json
/*
return response()->json(
[
'errors' => [
'status' => 401,
'message' => 'Unauthenticated',
]
], 401
);
*/
}
And it works fine. As the "Laravel" part will be used only as back end for APIs, it will be enough.
I am using laravel passport but when I try to hit the post route that gives me user data it's giving me error like
{"message":"Unauthenticated."}
here is my controller method
public function getDetails()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
api.php
Route::post('register', 'API\PassportController#register')-
>name('register');
Route::post('login', 'API\PassportController#login')->name('login');
//Route::post('details', 'API\PassportController#getDetails')->middleware('auth:api');
Route::group(['middleware' => 'auth:api'], function(){
Route::get('user', 'API\PassportController#user');
Route::post('details', 'API\PassportController#getDetails');
});
screenshot of postmen
please let me know what inputs you want from my side
Your codes look ok to me, but if I'm not mistaken you added your "Authorization" manually: please try this way from the image below, by clicking on Authorization tab, left next to Headers tab.
And make sure that your token is the one that is returned from the server when you make login request: see the image below.