I am trying to test laravel app using codeception.
Inside Laravel I am using Sentinel for authentication.
I have a problem to authenticate user inside tests.
Non of the following examples works:
$I->authenticateTestUser($I);
$user = \App\User::where('email','=','test#test.com')->first();
$I->amLoggedAs($user);
$I->canSeeAuthentication();
$credentials = [
'email' => 'test#test.com',
'password' => '****',
];
Sentinel::authenticate($credentials, true);
$I->canSeeAuthentication();
$I->amOnPage('/login');
$I->fillField('email', $email);
$I->fillField('password', $password);
$I->click('Login');
$I->canSeeAuthentication();
How I can authenticate in codeception functional tests?
You just have to use sentinel in the _before method :
private $_user;
private $_credentials;
public function _before(FunctionalTester $I)
{
// we create a user
$this->_credentials = [
'last_name' => 'Test',
'first_name' => 'test',
'email' => 'test#test.fr',
'password' => 'password',
];
$this->_user = \Sentinel::register($this->_credentials, true);
// we log this user
\Sentinel::authenticate($this->_credentials);
}
And you will be able to reuse your user or your credentials in your tests.
Related
This question already has answers here:
Where API credentials should be stored in laravel?
(2 answers)
Closed 4 months ago.
I am wiring an laravel web application for a small project.
One of the features is to access the API of a foto database (piwigo).
I am very new to laravel and have 0 experience in web security so I was wondering what is the best way to set it up.
I managed to setup the API access trough laravel by creating a PiwigoClient model with a login method, that will pass the response coockies to other request to piwigo:
class PiwigoClient extends Model
{
use HasFactory;
public static $apiURL = 'https://not-actual-piwigo-link/ws.php';
public function login() {
$response = Http::asForm()
->post($this::$apiURL . '?format=json', [
'method' => 'pwg.session.login',
'username' => 'UserName',
'password' => 'PassWord'
]);
return $response;
}
public function test() {
$login = $this->login();
$cookies = $login->cookies();
$response = Http::withOptions(['cookies' => $cookies])
->get($this::$apiURL, [
'format' => 'json',
'method' => 'pwg.tags.getImages',
'tag_name' => 'ImageTag'
]);
return $response->json();
}
}
Now I was wondering, it does not feel safe to leave the 'PassWord' like this in the PiwigoClient model file. What would be the safest and most convenient way to "store" the password?
Standard practices are to store "secret" keys in .env and then reference them in your codebase via a config file.
https://laravel.com/docs/9.x/helpers#method-config
// PiwigoClass
public function login() {
$response = Http::asForm()
->post(config('piwigo.url') . '?format=json', [
'method' => 'pwg.session.login',
'username' => config('piwigo.username'),
'password' => config('piwigo.password')
]);
return $response;
}
// config file piwigo.php
<?php
return [
'password' => env('PIWIGO_PASSWORD', 'PassWord'),
'username' => env('PIWIGO_USERNAME', 'UserName'),
'url' => env('PIWIGO_URL', 'https://my_api_url...')
]
?>
I'm testing api endpoint which is authenticated with laravel passport. I'm writing a feature test for checking if oauth/token can return a valid access_token. It is working fine in postman but I am using a different database for testing so when I run the test I'm always getting 400 error. Though I'm able to test all authenticated routes but I'm stuck when I want to test api/login or oauth/token endpoints. I'm running artisan command to install passport for test database. How to get client id and secret?
In TestCase class
public function setUp(): void
{
parent::setUp();
Artisan::call('migrate', ['-vvv' => true]);
Artisan::call('passport:install', ['-vvv' => true]);
Artisan::call('db:seed', ['-vvv' => true]);
}
LoginTest class
public function test_it_returns_a_valid_token_if_credentials_do_match()
{
$client = Passport::client();
$user = User::factory()->create([
'email' => $email = 'test#test.com',
'password' => $password = '12345678'
]);
$body = [
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $email,
'password' => $password
];
$this->json('POST', '/oauth/token', $body)
->assertStatus(200);
}
Here $client = Passport::client() return null. I didn't find any solution to get oauth client credentials.
Actually $client = Passport::client(); doesn't return client.
I have found a solution to create client from LoginTest.
$user = User::factory()->create([
'email' => $email = 'test#test.com',
'password' => $password = '12345678'
]);
$client = ClientFactory::new()->asPasswordClient()->create(['user_id' => $user->id]);
$response = $this->json(
'POST', '/oauth/token',
[
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $user->email,
'password' => $password,
]
)
->assertStatus(200);
I'm trying to test my login endpoint where a successful response would return the access_token among other things.
I'm using RefreshDatabase, so I changed the login method on the controller to retrieve the client_secret via a DB call. I tested with a dd() and I can confirm that the client_secret changes on each phpunit run in the terminal. The credentials are correct and the API endpoint works - just not when it's run via a test. For example, I have the passport tables set up on my mysql server and I can login successfully when running Postman. It's only when trying to run a test do I get a 401 error.
Here is my AuthTest
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class AuthTest extends TestCase
{
use RefreshDatabase;
/**
* #test
*/
public function a_user_receives_an_access_token()
{
\Artisan::call('passport:install');
$user = factory('App\User')->create();
$response = $this->json('POST', '/api/login', [
'username' => $user->email,
'password' => 'password'
]);
$response
->assertJson([
'access_token' => true
]);
}
}
routes/api.php
Route::post('login', 'AuthController#login');
AuthController#login:
public function login(Request $request) {
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2', //config('services.passport.client_id')
'client_secret' => DB::table('oauth_clients')->where('id', 2)->pluck('secret')[0], //config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() == 400 || $e->getCode() == 401) {
return response()
->json([
'status' => $e->getCode(),
'message' => 'Your email and/or password are incorrect',
'expanded' => $e->getMessage()
]);
}
return response()
->json([
'status' => $e->getCode(),
'message' => $e->getMessage()
]);
}
}
I took a look at this question and the accepted answer: How to test authentication via API with Laravel Passport?
I am unable to use the following
public function setUp() {
parent::setUp();
\Artisan::call('migrate',['-vvv' => true]);
\Artisan::call('passport:install',['-vvv' => true]);
\Artisan::call('db:seed',['-vvv' => true]);
}
This results in an error:
PHP Fatal error: Declaration of Tests\Feature\AuthTest::setUp() must be compatible with Illuminate\Foundation\Testing\TestCase::setUp()
Edit: I just added
public function setUp() :void {
parent::setUp();
\Artisan::call('migrate',['-vvv' => true]);
\Artisan::call('passport:install',['-vvv' => true]);
\Artisan::call('db:seed',['-vvv' => true]);
}
but the problem still persists
Edit again:
If I test the oauth route directly, it passes.
public function testOauthLogin() {
$oauth_client_id = 2;
$oauth_client = OAuthClient::findOrFail($oauth_client_id);
$user = factory('App\User')->create();
$body = [
'username' => $user->email,
'password' => 'password',
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client->secret,
'grant_type' => 'password',
'scope' => '*'
];
$this->json('POST','/oauth/token',$body,['Accept' => 'application/json'])
->assertStatus(200)
->assertJsonStructure(['token_type','expires_in','access_token','refresh_token']);
}
But my custom endpoint that uses guzzle fails. I do not know why
Edit again:
I think the issue is with Guzzle, but I'm not sure. I found another implementation of what I'm trying to do, which is the following:
public function login(Request $request) {
$request->request->add([
'username' => $request->username,
'password' => $request->password,
'grant_type' => 'password',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => '*'
]);
$response = Route::dispatch(Request::create(
'oauth/token',
'POST'
));
}
The above works.
Using laravel passport for token base authentication. i have set up scope for
access token and now on controller i wanted to get the scope value and its description.
protected function authenticate(Request $request)
{
$request->request->add([
'username' => $request->username,
'password' => $request->password,
'grant_type' => 'password',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => 'admin'
]);
$proxy = Request::create(
'oauth/token',
'POST'
);
$data = Route::dispatch($proxy);
//$data = json_decode($data);
return $data;
}
late to the party (I was looking this up myself) but check out the Passport::tokensCan array. You can define scopes and scope descriptions in there.
https://laravel.com/docs/5.8/passport#defining-scopes
I am working on a project where 3rd party apps can access data from Laravel server. I also have created a client application in laravel for testing.
Following code ask for authorization and its working fine.
Route::get('/applyonline', function () {
$query = http_build_query([
'client_id' => 5,
'redirect_uri' => 'http://client.app/callback',
'response_type' => 'code',
'scope' => '',
]);
return redirect('http://server.app/oauth/authorize?'.$query);
});
How can I authenticate a user before authorization? Right now I can access data form server using this code.
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://server.app/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'fcMKQc11SwDUdP1f8ioUf8OJwzIOxuF8b2VKZyip',
'username'=> 'ali#gmail.com',
'password' => 'password',
],
]);
$data = json_decode((string) $response->getBody(), true);
$access_token = 'Bearer '. $data['access_token'];
$response = $http->get('http://server.app/api/user', [
'headers' => [
'Authorization' => $access_token
]
]);
$applicant = json_decode((string) $response->getBody(), true);
return view('display.index',compact('applicant'));
});
Although above code works fine but I don't think its a good way to ask username and password at client side.
I want to use this flow (Same as facebook allows)
Click To Get Data From Server
Enter Username and Password
Authorize App
Access data for authenticated user
Well that was a stupid mistake. It works fine with authorization_code grant type. My mistake was that I was testing both server and client in same browser without logout. So client was accessing its own data from server. Also this flow diagram really helped me to understand the process of passport authorization.
http://developer.agaveapi.co/images/2014/09/Authorization-Code-Flow.png
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://server.app/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 5,
'client_secret' => 'fcMKQc11SwDUdP1f8ioUf8OJwzIOxuF8b2VKZyip',
'redirect_uri' => 'http://client.app/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);});