Symfony authentication event that fires only once? - php

I want to log logins.
But both InteractiveLogin and AuthenticationSuccess events fire on each request (because we use JWT to authenticate, which is passed as a header with every request), and the frontend does the redirection after a successful /api/login call, there is no way for me to know, whether the user just logged in.
How would you approach this?

If you are using a stateless firewall, as is the case when using JWT, the classic InteractiveLogin and AuthenticationSuccess are useless for this.
What you want to log is when the token is actually generated.
If you are using lexik/LexikJWTAuthenticationBundle, you could listen for a JWTCreatedEvent event to register that a user logged in.
class JwtCreatedSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
'lexik_jwt_authentication.on_jwt_created' => 'onJwtCreated'
];
}
public function onJwtCreated(JWTCreatedEvent $event): void
{
$user = $event->getUser();
// record your "last logged-in" according depending on your application set-up
}
}
If you are not using this bundle, well, it depends how you are generating your tokens in the first place. But the basic idea would be the same: check for token generation and log that time.
A caveat to take into account: if you are using any kind of "token refresh" to maintain sessions without needing to log-in again, each time you refresh the session you would generate a new token... and register a new log-in time.

Related

Laravel testing. Is possible to use multiple calls in same test?

I have this test:
public function test_user_can_access_the_application_page(
{
$user=[
'email'=>'user#user.com',
'password'=>'user1234',
];
$response=$this->call('POST','/login',$user);
$this->assertAuthenticated();
$response->assertStatus(302)
->assertRedirect('/dashboard')
->assertLocation('/dashboard');
$response=$this->call('GET','/application/index');
$response->assertLocation('/application/index');
}
After I log in, it directs me to the dashboard ok until now, but if I want to access the other page after that, I cant. This error comes up.
Expected :'http://mock.test/application/index'
Actual :'http://mock.test'
Aren't multiple calls allowed in the same test, or is another way to access other pages after login?
(Note: It's not possible to use factories for the actingAs so I need to login).
If you can't use factories for actingAs, then you should try with cookie.
Look at the https://github.com/firebase/php-jwt library.
I guess you will need to call the function as an user, since you can only access it logged in. Laravel provides the actingAs() method for such cases.
https://laravel.com/docs/7.x/http-tests#session-and-authentication
You can create a random User who has the permission to log into your app or take a seeded one and call the function acting as the chosen User.
$response=$this->actingAs($user)->call('GET','/application/index');
If you call it without actingAs(), your middleware will redirect you back to the login or home screen (what you defined in the LoginController ).
In my opinion this test case should have its own testing method. I recommend using a test method per route or per use case. It makes your tests clearly arranged and easy to understand.
If you want to be authenticated, the easiest way is to have PHPUnit simulate authentication using the actingAs() method.
This method makes the user authenticated, so you wouldn't want to test the login method with it. You should write your login tests separate from testing the other pages.
To answer your question, yes you can make multiple requests in the same test, but in this case linking the login test to the 'application/index' page likely does not make much sense.
public function test_the_user_can_login()
{
$user = [
'email'=>'user#user.com',
'password'=>'user1234',
];
$response = $this->call('POST','/login',$user);
$this->assertAuthenticated();
$response->assertStatus(302)
->assertRedirect('/dashboard')
->assertLocation('/dashboard');
}
public function test_user_can_access_the_application_page()
{
$user = User::where($email, "user#user.com")->first();
$response = $this->actingAs($user)
->call('GET','/application/index');
$response->assertLocation('/application/index');
}
I experienced that in laravel 8 I use comment #test and involved second test!!! I mean if you use two function for test you must us #test that php artisan test, test both of them.

How to bypass usual Laravel authentication process to set a user as logged in

I am building a new Laravel application (v5.4) that will run alongside (installed in the same environment) an existing PHP application that has it's own authentication system. I want the users who have successfully logged in to the existing system to be automatically authenticated in the Laravel app so they can navigate seamlessly between the applications.
My Laravel app has read-only access (through a second db connection) to the existing system's database so it can safely check that the PHP Session matches the session cookie recorded in the database and I can even pull out the user object and hand it to Auth's login() method.
I want to know the best way to put Auth into an authorised state (not guest) and where is the best place to put such code?
Options I've thunked of so far:
Middleware: Check session and call the login() method on Auth from some application-wide middleware?
Extend Illuminate/Auth/SessionGuard.php and override the attempt() method? If so, how do I tell the other parts to use my extended SessionGuard? (I suspect this was not designed to be easily overridden)
Super hacky disgusting way of dynamically setting the user's password to a random hash and then calling Auth/LoginController#login() in the background with a faked request containing that hash as the password field. (I seriously hope this doesn't end up being the most popular answer)
Some other option (?)...
Thanks in advance for your help SO community!
The solution I ran with in the end was creating a middleware that contains this:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isSet($_SESSION['intranet_user_id']) && $_SESSION['intranet_user_id']) {
// Log them in manually
$intranet_user_id = $_SESSION['intranet_user_id'];
if (!Auth::guest() && Auth::user()->getId() !== $intranet_user_id ) {
Auth::logout();
}
if (Auth::guest()) {
Auth::login( User::find($intranet_user_id), true);
}
} else {
Auth::logout();
}

Properly implementing resource authorization for a RESTful API

My team has an API we wrote in PHP using the Slim Framework. It's being consumed by a web app and a third party mobile app.
We use the standard OAuth 2 workflow to provide access to our resources. We can see if someone is a sending a valid access token along with the API request and that part of the flow makes sense.
The stumbling block we're running into is how to most efficiently authorize access to a resource depending on the permissions of the user associated with the access token.
For the sake of simplicity let's say that we just want to ensure that the owner of the resource in question matches the owner of the access token. To me that seems like something that a route middleware would handle, for every request, before processing the request make sure that the resource owner ID matches that of the access token.
The problem in my mind is that resource permissions aren't necessarily consistent across all routes, a route isn't necessarily going to have an ID in the same section of the URI, it might not have an ID in the URI at all, etc. etc.
My current solution has been to have an authorization utility class that takes in an email and checks it against the user that's currently "logged in" (token owner).
class Authorization() {
checkResourcePermissions($email) {
if (loggedInUser->email == $email) {
return true;
}
}
}
Obviously this is a simplification, but what this means is that since a route middleware won't have the context of a request until that request goes through I will need to call this authorization method inside of every API route, responding with an error if necessary, etc. Our API is fairly large, essentially boiling this down to a large amount of copy and paste which always makes me very nervous.
What am I missing?
I'd suggest going the way using a 'normal' MiddleWare:
First, let's assume you have a class 'user', where you implement your logic to access various types of resources or has specific permissions, given only the $app. It can access the request and get any information from a the HTTP request necessary to identify a single user.
class User{
private $userid=false;
public function __construct($app){
$this->app=$app;
$users_mail=$this->app->request->post('email');
//SELECT user_id FROM USERSTABLE WHERE email = $users_mail
//$this->userid=user_id
}
public function ensureHasAccess($resourceID,$redirect='/noPermission'){
if(!/*some DB Query which returns true if this user may access the given $resourceID*/)
$this->app->redirect($redirect)
}
public function ensureHasRole($role) {
//some other permission checking, like ensureHasAccess();
}
public function ensureIsUser(){
//do Something
}
}
Next, you'll need a MiddleWare which is run before the route is dispatched, and creates an User-Object:
class UserPermissionMiddleware extends \Slim\Middleware{
public function call(){
$this->app->request->user = new User($app);
$this->next->call();
}
}
Then, simply add this Middleware:
$app->add(new UserPermissionMiddleware());
Now, you can modify every route to check the access to a resource, while the resource id (of course) still needs to be supplied by hand, according to the route-specific code:
$app->get('/resource/:id',function($resourceId) use ($app){
$app->request->user->ensureHasAccess($resourceId);
//deliver resource
});
If the user is not allowed to access this resource, the whole process is interrupted (Note that redirect() is implemented using Exceptions!) and another route is executed. You'll still need some code in every single Route, but if there's no consistent way to determine the resource to be acccessed, there'll be no way around this.
Hope this helps you so far. If you have any Questions, feel free to ask!

how to cancel authentication in AuthenticationSuccessHandler?

I made a child class that extends from DefaultAuthenticationSuccessHandler in order to add custom feature during the authentication process. I want to stop the authentication process if the criteria is not met. How do I do that?
public function onAuthenticationSuccess( Request $request, TokenInterface $token) {
if(some_condition_applies){
//if success, resume default flow
return parent::onAuthenticationSuccess( $request, $token);
}else{
//how to fail the authentication here?
}
}
AuthenticationSuccessHandler's main purpose is to do something AFTER the user has been authenticated. In other words it is too late to do anything about it.
You can create a custom authentication provider which handles all the authentication logic you require.
http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html#the-authentication-provider
Depending on your setup, the new SimpleFormAuthenticator functionality in Symfony 2.4 may help you out: How to Create a Custom Form Password Authenticator
This is probably only applicable if your authentication mechanism is username/password based (not OAuth or something).
Additionally, you could potentially just implement the AdvancedUserInterface, and then return "false" from a method like "isEnabled" to prevent login (Forbid Inactive Users). The only disadvantage is that you only have access to data in your User class. If you need something beyond that, the above method should work (but is a little bit more work).
Cheers!

automatically login user if they are guest with Yii

I've been handed off some code that for legacy reasons must keep using the Yii framework. Though when a user comes to a certain page as a guest I need the page to automatically log them in as a certain user. After browsing both the Yii documentation and here I have not found any solutions to this problem. Is what I am trying to do possible with Yii?
I would use Behaviors to do this, probably onBegnRequest. This will fire before every request is handled, and automatically log a user in if they're currently a guest
<?php
class BeginRequest extends CBehavior
{
public function attach($owner)
{
$owner->attachEventHandler('onBeginRequest', array($this, 'handleBeginRequest'));
}
public function handleBeginRequest($event)
{
if(Yii::app()->user->isGuest())
{
$identity = new UserIdentity('known-user', 'known-password');
// authenticate identity or not, up to you if you know which user should be logged in
Yii::app()->user->login($identity);
}
}

Categories