Creating Custom Authentication in Laravel - php

i have project which is developed in core php .Now i have created few api in that
I am able to get all data in laravel but now i have bit problem with login authentication .
public function postLogin(Request $request) {
// print_r($request->all());
$data['email']=$request->email;
$data['password']=$request->password;
$response= ApiModel::userLogin($data);
// Auth::login($response[0]);
// Auth::loginUsingId($response[0]->id);
echo "<pre>";
print_r($response[0]);
}
I am trying to create authentication session but its giving error. i have tried following methods but it seems to be not working
Auth::login($response[0]);
Auth::loginUsingId($response[0]->id);
Can any one help me how to keep user session using api
Error
ErrorException in SessionGuard.php line 408: Argument 1 passed to
Illuminate\Auth\SessionGuard::login() must be an instance of
Illuminate\Contracts\Auth\Authenticatable, instance of stdClass given,
called in
D:\xampp\htdocs\collab\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php
on line 294 and defined

you can use Auth::attempt(['fieldname'=>'value','someother'=>'anothervalue']);

You need to define the correct auth guard information in config/auth.php. The Auth::login() method expects you to pass a User model instance by default and this model should implement Illuminate\Contracts\Auth\Authenticatable.
You should set the default guard provider to use database driver instead of eloquent and set the correct table name. You can then use Auth::loginUsingId() to login a user using their id.
But if you do not want to connect your database to Laravel then just rely on the API response and perform your action based on that. You cannot force an authenticated session this way.

Related

How works "extend" of Storage facade in Laravel, and why my code behaves so strange?

I want to add additional cloud driver to my lumen app like this:
Storage::extend('s3_v2', static function ($app, array $config) {
return (new FilesystemManager($app))->createS3Driver($config);
});
So, it work's. And it's a problem. When i use Storage::put()/makedir() etc. it works, even if I've another cloud driver by default. Code in closure isn't working (Log::info()
for e.x.), may be cause i use another S3 cloud driver but if i delete this fragment of code, i'll have this error:
Credentials must be an instance of
Aws\Credentials\CredentialsInterface, an associative array that
contains "key", "secret", and an optional
"token" key-value pairs, a credentials provider function, or
false. (500 Internal Server Error)
If i change driver to current default it will work and all additional logic in callback execute:
Storage::extend('minio', static function ($app, array $config) {
Log::error('test'); // Log successful output-ed
return (new FilesystemManager($app))->createS3Driver($config);
});
Its works... and not? It's like it isn't entering into the closure if i use another driver, but it's registering that driver...
So if i'm extending current driver its will register it and will execute callback (???)
So i'm very confused.
Just to be clear, i don't have other Storage::extend anywhere more in my app. And if:
Storage::extend('ASDASDASD', static function ($app, array $config) {
return (new FilesystemManager($app))->createS3Driver($config);
});
Its also allows me to properly works with my current cloud driver, but callback don't executes. I can verify this by opening minio console and seeing the added files there
I've found answer to my question.
Method "extend" of storage facade will perform regardless of given driver name and its callback.
It's just adding given callback to array property of FilesystemManager instance with key from first argument.
It's also performs register of all drivers from configuration, not only added in the first argument.

Laravel Socialite Implement stateless for Twitter

I would like to implement stateless method to Twitter but it seems that it is not available for TwitterProvider class as it returns
Call to undefined method Laravel\Socialite\One\TwitterProvider::stateless()
Here is my redirectToProvider method currently.
public function redirectToProvider($socialMedia)
{
$provider = strtolower($socialMedia);
return Socialite::driver($provider)->stateless()->redirect();
throw new NotFoundHttpException;
}
What is the correct implementation or what do I miss?
As mentioned by #driesvints from this question #415 I've opened at the Laravel Socialite repository, stateless is unavailable for Twitter since it uses OAuth 1.0.
They already pushed a PR #5661 to update also the Laravel Docs mentioning this specification. Click the link to see the update. Staless Authentication
I would update this answer if whatever my solution would be.

SimpleSMLphp Custom Module Authentication Triggering Twice

Background: I am trying to set up single sign on (SSO) for users such that they can authenticate to my website and not have to authenticate a second time to our third-party MSP's website. Ideally, the user clicks a link on our website and is taken to the third-party site already logged in and landing on the dashboard (if the account doesn't exist, it is created during this step). We are not using SAML for authentication as a security feature, so all that we need the SAML code for is just producing cookies that prevent the user from having to log in again when he/she gets to our vendor's site. This third party MSP does not support authentication via API or web service and therefore I have been tasked with implementing SAML, their only supported SSO method. I am new to SAML (but not PHP or development) and have been learning as I go. I am told it will support the goals described above.
I initially tried using LDAP as the authentication source as this is what I use for authentication to my website, but this resulted in me getting directed to a login page with no discernible way to instead just pass parameters to SimpleSAMLphp to tell it "the user is already authenticated, all I need you to do is give me valid cookies so I can get past the third party website's authentication checks".
So I switched to writing a custom authentication module. I opened up the GitHub for SimpleSAMLphp and used the "UserPassBase" class as an example to create my own authentication module that inherits from the "Source" class. Because I don't need to re-authenticate the user against LDAP a second time since they're already logged in to our website, I created a simple "authenticate" function that just sets the $state['Attributes'] array.
Here is the code for my custom module:
<?php
namespace SimpleSAML\Module\productauth\Auth\Source;
use SimpleSAML\Auth;
/**
Author: Joey
Class developed to be used as a custom authentication module for simpleSAMLphp. This class will take an existing session from a product website and use it to create a SAML session and redirect to a website.
**/
class ProductAuth extends \SimpleSAML\Auth\Source {
const STAGEID = '\SimpleSAML\Module\productauth\Auth\ProductAuth.state';
const AUTHID = '\SimpleSAML\Module\productauth\Auth\ProductAuth.AuthId';
private $user;
public function __construct($info, $config) { // parameters aren't used, just filler from base class
$info = array("AuthId" => "productauth");
parent::__construct($info, $config);
}
public function login($user, $redirectURL) {
$this->user = $user; // normally I'd set this in the constructor, but the overload has my hands tied as far as function definitions go
$this->initLogin($redirectURL); // calls authenticate function and then, if no exceptions, parent::loginCompleted which redirects to the given URL
}
public function authenticate(&$state) { // called by parent::initLogin
$state[self::AUTHID] = $this->authId;
$state['Attributes'] = [
'uid' => [$this->user->uid],
'givenName' => [$this->user->givenName],
'sn' => [$this->user->sn],
'mail' => [$this->user->mail]
];
$id = Auth\State::saveState($state, self::STAGEID);
}
}
?>
I am calling it from a controller class on my website:
private function goToTrainingSite() {
require_once("../third-party-libs/simplesamlphp/_include.php");
global $TRAINING_URL;
$user = $_SESSION['subject']->user;
$samlObj = new SimpleSAML\Module\productauth\Auth\Source\ProductAuth(array(), array());
$samlObj->login($user, $TRAINING_URL);
}
I mimicked the flow of the "UserPassBase" class (https://github.com/simplesamlphp/simplesamlphp/blob/master/modules/core/lib/Auth/UserPassBase.php), but it seems that despite all of my authentication working and setting a SimpleSAMLAuth cookie, when the parent::loginCompleted function in the "Source" class (https://github.com/simplesamlphp/simplesamlphp/blob/master/lib/SimpleSAML/Auth/Source.php) runs, it redirected me to the third party site. I then see the following in the logs:
SAML2.0 - IdP.SSOService: incoming authentication request: [REDACTED DATA]
Session: 'productauth' not valid because we are not authenticated.
I have been trying for 3 days to figure out why it seems as though despite setting SimpleSAML session cookies with a completed, successful authentication, that upon receiving the auth request from the SP, my SimpleSAMLphp code just pretends to not know about the completed auth and tries to authenticate again... but because it is not being called from my code, it doesn't have access to the $user variable which contains all of the attributes I need to place on the user when he/she authenticates to this third party website. It seems that when it receives an authentication request, my SimpleSAMLphp installation starts a new session and tries a brand new authentication.
I have delved into a lot of the code of SimpleSAMLphp and tried to understand what is going on, but it seems that there is just no reasonable way to authenticate by calling an authentication source from PHP code and being able to skip the SP-initiated authentication. I have tried:
Using the SimpleSAML API (https://simplesamlphp.org/docs/stable/simplesamlphp-sp-api) to call my authentication source, but there seems to be no way to pass that $user variable I need the attributes from.
Trying to load the cookies in the "Session" class when it is checking for valid sessions... but it seems like the cookies from the successful auth session initiated by my code are just gone and nowhere to be found.
I decided to stop focusing on trying to get the $user variable and the data I needed to the second authentication, and instead focus on WHY the second authentication was even happening. I looked at the cookies and thought about how the data was being retrieved, and made a correct hunch that our application's custom session handler might be at fault for SimpleSAMLphp's inability to recognize the first authentication. Our custom session handler stores our sessions in the database, but SimpleSAMLphp expects to use the default PHP session handler to manage its session. Therefore, my first authentication was being sent to the database and when SimpleSAMLphp started looking for it where PHP sessions are usually stored, it didn't see it and assumed it needed to kick off another authentication session from scratch.
Using SimpleSAMLphp's documentation for service providers and a lot of my own debugging, I changed the function in my controller like so:
private function goToTrainingSite() {
require_once ("../third-party-libs/simplesamlphp/_include.php");
global $TRAINING_URL;
$joeySiteSession = $_SESSION;
$user = $_SESSION ['subject']->user; // save user to variable before the Joey's Site session is closed
session_write_close (); // close Joey's Site session to allow SimpleSAMLphp session to open
session_set_save_handler ( new SessionHandler (), true ); // stop using SessionHandlerJoey and use default PHP handler for SimpleSAMLphp
$samlObj = new SimpleSAML\Module\joeysiteauth\Auth\Source\JoeySiteAuth ( array (), array () );
$samlObj->login ( $user, function () { return;} ); // use custom authentication module to set atttributes and everything SimpleSAMLphp needs in the auth session/cookie
$session = \SimpleSAML\Session::getSessionFromRequest ();
$session->cleanup (); // must call this function when we are done with SimpleSAMLphp session and intend to use our Joey's Site session again
session_write_close ();
$_SESSION = $joeySiteSession; // restore Joey's Site session
header ( "Location: {$TRAINING_URL}" );
}

Laravel cookie unexpected output i.e. encrypted result on service provider

I am developing a package where I am registering ServiceProvider and inside my class methods I am saving cookie data as this
Cookie::queue(Cookie::make('my_name', 'manash', 120));
and I am retrieving like this
Cookie::get('my_name')
but I am not getting the value as I have stored, instead it is outputting me this value
eyJpdiI6InlcL3VxNklrejlKemxLQ012T0pcL3U1QT09IiwidmFsdWUiOiJpbzRmajVEUU90YkhhdTdpeFNlcURBPT0iLCJtYWMiOiI1MTFiMTk5YjY3ZTczMzI2Nzc1MGI1Mzk3NmU1MjJhYjE3MWRhYWE2OGQ4NWE1Y2Y2NDgyZWQ1YmYxOGQ4OWU1In0=
I think it encrypted, but as per my knowledge it should be automatically decrypted when we use get method.
I am using laravel 5.3.28
What happens is that all cookies created by laravel are encrypted and signed with an authentication code.
Have you tried with the request?
Like this:
Illuminate\Http\Request
Request $request;
$request->cookie('my_name');
Check if your middleware is not triggering before Encrypt Cookie middleware
Try https://laravel.com/docs/master/encryption see if it works

Unable to get access token from instagram

Im using this instagram wrapper package for laravel 5.1. Im trying to connect to instagram thorugh the API then auth a user in using
use Vinkla\Instagram\Facades\Instagram;
public function instagramlogin(Request $request)
{
// Get code parameter.
$code = $request->get('code');
// Request the access token.
$data = Instagram::getOAuthToken($code);
// Set the access token with $data object.
Instagram::setAccessToken($data);
// We're done here - how easy was that, it just works!
Instagram::getUserLikes();
// This example is simple, and there are far more methods available.
}
and then be able to get access to his/her profile data. but I keep getting an error stating
ErrorException in Instagram.php line 526:
Undefined property: stdClass::$access_token
How do I auth a user?
I solved this problem. You basically have to use the cosenary instagram package as this package is a wrapper for that package. So if you run through the documentation on the cosenary package and use facades instead, the functions will work.

Categories