Laravel Ratchet socket Auth - sockets

I am starting learning Ratchet (reactPHP) I am using laravel. But I came to a line about security.
How can I deny websocket connection based on user is logged in or not
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
$this->users[$conn->resourceId] = $conn;
if(Auth::check()){
echo 'user logged in';
}else{
echo "New connection! ({$conn->resourceId})\n";
}
}
I used something like this but it passes the Auth::check and console always shows New Connection.

Ok Playing around found solution and it seems ok:
I am using Sentinel
$session = (new SessionManager(App::getInstance()))->driver();
$cookies = $conn->WebSocket->request->getCookies();
$laravelCookie = urldecode($cookies['timeline_auth']);
$idSession = Crypt::decrypt($laravelCookie);
$user = Sentinel::findByPersistenceCode($idSession);
If there is better solution please leave a comment

You cannot use Auth::user() anymore with WebSocket. The WebSocket server is handling multiple connections (so Auth::user() dosent have any sense). BUT you can access the user session.
more details here
https://laravel.io/forum/01-16-2015-loading-laravels-session-using-ratchet

Use laravel-ratchet package.
It will handle connection to auth conversion and laravel session for you.

Related

ejabberd: Saving of roster not working with external Authentication Script enabled

I have successfully configured an ejabberd server with an extauth script (perl).
It is working correctly and only allowing users from my mysql DB.
But following features are not working anymore: roster management, adding users to rosters, authorization of users (for adding them to the roster)
With the internal auth it works. Both times ejabberd is configured to use the internal amnesia db.
Please help me figure out, why it is not working with extauth enabled. Do I have to write my own methods in the extauth script? (That I don't really want...)
So after doing some research on my problem, I think that switching to the external authentication will not support roster management.
What I ended up doing is swichting back to internal authentication and using mod_admin_extra to add users and update passwords with this php script:
<?php
class Jabber
{
public static function registerAndAddToSharedRoster($userId, $sessionToken)
{
$url = "http://localhost:5280/rest";
$register = "register $userId jabber.YOUR_DOMAIN.com $sessionToken";
sendRESTRequest($url, $register);
$sharedRoster = "srg_user_add $userId jabber.YOUR_DOMAIN.com shared jabber.YOUR_DOMAIN.com";
sendRESTRequest($url, $sharedRoster);
}
public static function updatePassword($userId, $newPassword)
{
$url = "http://localhost:5280/rest";
$register = "change_password $userId jabber.YOUR_DOMAIN.com $newPassword";
sendRESTRequest($url, $register);
}
}
function sendRESTRequest ($url, $request)
{
// Create a stream context so that we can POST the REST request to $url
$context = stream_context_create (array ('http' => array ('method' => 'POST'
,'header' => "Host: localhost:5280\nContent-Type: text/html; charset=utf-8\nContent-Length: ".strlen($request)
,'content' => $request)));
$result = file_get_contents($url, false, $context);
return $result;
}
?>
Hope this helps someone!
This answer is late but it could help someone:
Contrary to #ben-marten's answer, Switching to the external authentication does support roster management.
When you add someone to the roster, ejabberd is 'calling' the isuser operation - check if it’s a valid user - you have to provide that method in the script: see ejabberd Developers Guide - External Authentication
I ignored that operation, and I could not add a user to the roster.
For other script examples see Authentication Scripts

fetch emails with php lib that suports oauth 2

I'm trying to get mail(imap) from google by oauth authorization . I have got the authorization to work, but I can not retrieve the emails. As I understand it should be posible. But Google does not have any api to retrieve mail(?). However, I found the following:
https://developers.google.com/google-apps/gmail/oauth_overview
That says:
Accessing mail using IMAP and sending mail using SMTP is often done
using existing IMAP and SMTP libraries for convenience. As long as
these libraries support the Simple Authentication and Security Layer
(SASL), they should be compatible with the OAuth mechanism supported
by Gmail. In addition to using a library which supports IMAP and SMTP,
developers also will want to use one of the many existing libraries
for handling OAuth
Do anyone know a existing library that i can use and that has some documentation as well. Im using google-api-php-client.
The code
session_start();
ini_set('display_errors',1);
error_reporting(-1);
require_once '../../src/apiClient.php';
$client = new apiClient();
$client->setApplicationName('Mailendar');
$client->setScopes("http://www.google.com/m8/feeds/");
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
$client->setClientId('secret');
$client->setClientSecret('secret');
$client->setRedirectUri('secret');
$client->setDeveloperKey('secret');
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
echo "token is set";
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
MAGIC HAPPENS HERE!!!...but is unkown for me ofc
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
}
if (isset($auth)) {
print "<a class=login href='$auth'>Connect Me!</a>";
} else {
print "<a class=logout href='?logout'>Logout</a>";
}
Thanks!
Google doesnt allow you to retrieve mail with oauth 2.0 at the moment.
Now you can fetch mails using OAuth.
Implemented a simple library.
Delete mail function is not yet added. But you can take a look if it satisfies your need.
Try example. https://github.com/vmuthal/VivOAuthIMAP

Smack service discovery without login gives bad-request(400)

I am trying to discover items that a pubsub service provides. When I log into the target server, I can get the response successfully. But when I connect bu do not login, it gives a bad request error.
This is the code:
ConnectionConfiguration config = new ConnectionConfiguration(serverAddress, 5222);
config.setServiceName(serviceName);
connection = new XMPPConnection(config);
connection.connect();
connection.login(userName, password); //!!!when I remove this line, bad request error is received
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
DiscoverItems items;
try {
items = discoManager.discoverItems("pubsubservice." + serverName);
} catch (XMPPException e) {
e.printStackTrace();
}
Is there a way to discover items when the user is not logged in, but the connection is established?
No, you must authenticate to send stanzas to any JID in XMPP (otherwise they would not be able to reply to you, since they wouldn't know your address).
Perhaps one option for you is anonymous authentication. Most servers support it, and it creates a temporary account on the server for you, with a temporary JID. You don't need a password, and login time is quick.
#MattJ is correct and you could try using anon login. That will get you part way there.
Your current request will only get you the nodes though, after which you will have to get the items for each node. It would be simpler to use PubsubManager to get the information you want since it provides convenience methods for accessing/using all things pubsub.
Try the documentation here, the getAffiliations() method is what you are looking for.
BTW, I believe the typical default service name for pubsub is pubsub not pubsubservice. At least this is the case for Openfire.

Is there any tools to check what is happening in Kohana at Auth?

So, there is problem - I have the order to write web-app on Kohana (no choice) and until yesterday I had no experience with this framework (only in Rails). But anyway I googled and created the authentification on site via net steps:
1: using standart SQL-code in Kohana I created tables for Auth.
2: tutn on ORM and Auth
3: create action login()
public function action_login()
{
$auth = Auth::instance();
if ($auth->logged_in())
{
return $this->request->redirect("welcome/view");
};
if ($_POST)
{
$user = ORM::factory("user");
$status = $auth->login($_POST["username"],$_POST["password"]);
if ($status)
{
$this->request->redirect("welcome/view");
}
else
{
echo "Failed to login";
}
};
$this->response->body(View::factory("login"));
}
But whatever I do I get echo "Failed to login";.
Is there any tools to define what's wrong happening ? Some logs ?
Or, may be, I do something wrong at common....
To answer your question: no there are no obvious tools to dig into Auth. You're best off going into modules/auth and look into the files and dump out information to Kohana::log or Kohana::debug to debug the errors.
I think the problem with your code is that in Kohana 3.2, $_POST is unset. You should use this instead:
$status = $auth->login($this->request->post("username"), $this->request->post("password"));
Should work after that.

Adding authentication functionality to soap server (Using Zend)?

I have a soap server that is created like so:
class ServerController extends Zend_Controller_Action
{
public function serverAction()
{
memcache_flush();
Zend_Registry::get('cache')->clean(Zend_Cache::CLEANING_MODE_ALL);
$server = new SoapServer("http://####/services/soap-server/wsdl");
$server->setClass('SOAP_Server_Map');
$server->handle();
}
}
I want to add authentication to it so that whenever anyone makes a call to a function in "SOAP_Server_Map", it checks that the credentials supplied in the SoapClient options array('login' and 'password') are valid.
Does anyone have any suggestions/help?
To add authentication to either Zend_Soap_Server or Zend_Json_Server, simply specify the HTTP authentication in either your HTTP server (ie: Apache) config or .htaccess file. The following .htaccess file should work:
AuthType Basic
AuthName "Supreme Data Services"
AuthUserFile /var/www/localhost/passwd
Require valid-user
Make sure you keep your password file out of the docroot for security purposes. The password file can be made by using htpasswd that comes with Apache. Naturally, you can use more advanced authentication types.
In order to make use of the service(s), you must now specify a username and password when making a request. If you are using Zend Framework to create your client, you can do the following for SOAP:
$client = new Zend_Soap_Client($wsdl, array('login' => $username, 'password' => $password));
And the following for JSONRPC:
$http = new Zend_Http_Client();
$http->setAuth($username, $password);
$client = new Zend_Json_Client($uri, $http);
Try this: http://pt.php.net/manual/en/soapclient.soapclient.php#101503
I have exactly the same problem and I have the following thoughts:
I do not know if SOAP is/should be state-full or stateless, can we open a session and if the user has supplied some form of credential keep her logged in for some period of time?
The other way I am thinking of solving this is through API-keys, say for example giving a key: ABCDKEY and having the url as:
http://####/services/soap-server/ABCDKEY
This introduces security risks (the magic link attack), but I've seen it implemented in RSS personalized feeds etc.
Any comments?