I'm working with a .net server solution that provides an authentication web service, along with several other service URLs. The access process involves an initial call to the authentication service URL, and using an 'Authenticate' soap call, which is supposed to return an access token. This token is then used to make calls to the other service URLs to retrieve data from the server.
The issue I'm having is that I was provided a username and password for the authentication process, but there's no indication of how the credentials are meant to be sent to the server. Additionally, I'm trying to access the web service (.net based) using PHP.
So far, I've managed to use wsdl2php to generate classes for the authentication service URL, but the classes don't provide any indication of how the username and password are meant to be sent.
I've tried adding the credentials as soap headers:
$headerContent = "<o:UserName xmlns:o=\"$namespace\">
<o:UserName>$uname</o:UserName>
<o:Password>$pword</o:Password>
</o:UserName>";
$headerVar = new SoapVar($headerContent, XSD_ANYXML, null, null, null);
$header = new SoapHeader($namespace, 'o:ClientCredentials', $headerVar);
$this->__setSoapHeaders(array($header));
try {
return $this->__soapCall('Authenticate', array());
} catch (Exception $e) {
throw new Exception( 'Not allowed.', 0, $e);
}
...but I receive an 'Access denied' message. Is there a proper way to pass the credentials to the service in order to successfully authenticate?
There are many different authentication flavors - forms, basic, oauth. If you have a way to login via a browser, I would suggest running Fiddler to peek at the message traffic. Fiddler is a middleware tool that sits between the browser and server. It will give you the packet headers - so you can see the encryption, field formatting and content type. You should then mimic the request.
Related
I am currently redoing a legacy web application that uses the PHP Parse SDK, and I am in the login authentication part. In the old application, we used $ _SESSION and ParseToken when doing ParseUser::signIn() and ParseUser::currentUser() to check if you have a session with a valid token, however the new application is being made using the REST architecture, where one of the REST concepts is that the server must not keep state, that is, be stateless, and in that case it would be the client that would have to send the necessary data.
When searching the internet and forums, I saw that it is common for developers to authenticate with JWT, where the client would make a request for a server's route and the server would return a token, and through that token authentication would take place.
I even implemented something using Firebase / jwt-php, where the client [Postman] makes a request for the route /login sending via body [username, password] and in case of success, returns the token to be used in secure route requests.
NOTE: Code is as simple as possible, without validation and cleaning just to show the example.
Action /login
$username = $request->getParsedBody()['username'];
$password = $request->getParsedBody()['password'];
$userAuthenticated = ParseUser::logIn($username, $password);
$payload = [
'data' => $userAuthenticated,
'exp' => time() + 3600
];
$token = JWT::encode($payload, $_ENV['JWT_SECRET_KEY']);
echo json_encode(['token' => $token]);
And the protected routes have a middleware that checks if the time has expired, and if this has happened, an exception with a 401 code is launched.
So far so good, authentication works, the problem I don't know if it's right to do it this way, since I need to give a ParseUser::logIn(), just to generate a session in the database and I don't even use it this session to do some authentication, with the exception of operations in the bank, because from what I saw in the documentation, if there is no valid session in the database, the application will return invalid session token error and also when making the request for another route ParseUser::currentUser() returns null, and this may be a problem in the future.
Does anyone have any idea how I can implement authentication for a REST application made in PHP? I appreciate the help !!
I believe the easiest way would be just replacing the default session storage (which uses $_SESSION) to something else that stores the session in, for example, Redis. Reference: https://docs.parseplatform.org/php/guide/#session-storage-interface
But the way you are doing should also work. You will only have to make sure that, every time that a request comes, you will decode the JWT, get the Parse Session token from there, and use ParseUser::become to set the current user: https://docs.parseplatform.org/php/guide/#setting-the-current-user
I just learn how to create a web service and consume it using PHP and (nusoap). now I am confused on how to authenticate a web service URL.
For example I have a web service that has a URL like below
<?php
include_once './lib/nusoap.php';
$server = new nusoap_server();
//print_r($server);
$server->register('abc');
function abc()
{
return 'welcoem';
}
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
localhost/nusoap/webservice91.php
So I give it to a client. but I want to know is that particular person is using web service to whom I give them a URL.
How to get to know if another person is using our web service.
There are several options technically:
HTTP authentication
Soap-based authentication via soap headers.
Roll-your-own authentication with username/password or token being embedded in the soap body as part of the actual request.
I have a browser-based app (single page, AngularJS) and am using hello to use third party signin such as Google, FB, Soundcloud, etc.
My app uses a PHP API server.
What's a good way to have the user able to login using Google, but also verify the user on the server side?
I was considering:
The browser app performs an implicit grant with google/fb/etc
I then transfer the access_token from the client to the server, then use, for example, a google-api-php-client with my app id, secret and the user access_token? Using their API such as /me? (which grant type would this be?)
Retrieve some key from the third-party (facebook_id, email, etc), match it against a user in my database, and then consider the user authenticated?
Also, should I perform this on each API request? Or should I just stash the access_token for a bit and assume that the user is still valid until the key expires?
One issue is that not all of those providers support the implicit flow. But assuming they do, the access_token you get for each will be proof that the user authenticated with that system, not necessarily that they have access to call your API. You still need something that asserts that "someone#gmail.com can 'read' resource X in your system"
You probably need something that translates whatever you get from Google, Soundcloud, etc. into a token your app understands. A simple(r) format is to use JWT. (Json Web Tokens).
App -> Intermmediary -> Soundcloud/Google
<-JWT--+ <---whavetever-+
and then:
App - (JWT) -> API
JWT are easy to manipulate, validate and verify. See jwt.io
You might want to look at this blog post also for some additional information (specifically on AngularJS front-ends)
The blog post #eugenio-pace mentioned was really helpful for setting up the client side.
For the server side though, the access_token should be validated.
The SDK's are (in composer) (code below):
Facebook: "facebook/php-sdk-v4" : "4.0.*"
Google: cURL request (didn't care for "google/apiclient")
SoundCloud: "ise/php-soundcloud": "3.*"
(There are others of course, just these three were the ones I chose, and seem decent.)
Last time I did something like this I made the mistake of validating the access_token on every request, which had a huge (obviously negative) impact on performance. Now I just validate it on login and use it to retrieve the user's ID from that service. So, the browser sends me access_token A and says it's from Facebook, I use the sdk above the the access_token with Facebook, and I get back their ID so I know they are who they say they are.
I'd suggest storing the access_token on the server with the expires_in.
(I haven't dealt with refresh token's yet)
Code to validate tokens using the above libraries:
function validateTokenFacebook($token, $id=null) {
// Performed above
// FacebookSession::setDefaultApplication($config->fb->app_id, $config->fb->secret);
$session = new FacebookSession($token);
// Fetch user info
$request = new FacebookRequest($session, 'GET', '/me');
try {
$response = $request->execute();
} catch (\Facebook\FacebookServerException $e) {
$this->mlog->err($e . "\n" . $e->getTraceAsString());
throw new AuthTokenInvalidException();
}
$graphObject = $response->getGraphObject();
$user_id = $graphObject->getProperty('id');
return array(access_token, $user_id);
}
function validateTokenGoogle($token, $id=null) {
$resp=array();
// This key isn't included in the token from hello.js, but
// google needs it
if (!array_key_exists('created', $token)) $token['created'] = $token['expires'] - $token['expires_in'];
$client = new \Google_Client();
$client->setClientId($this->systemConfig->google->app_id);
$client->setClientSecret($this->systemConfig->google->secret);
$client->setRedirectUri($this->systemConfig->google->redirectUri);
$client->setScopes('email');
$client->setAccessToken(json_encode($token));
try {
// Send Client Request
$objOAuthService = new \Google_Service_Oauth2($client);
$userData = $objOAuthService->userinfo->get();
return array($token['access_token'], $userData['id']);
} catch (\Google_Auth_Exception $e) {
throw new AuthException('Google returned ' . get_class($e));
}
}
function validateTokenSoundcloud($token, $id=null) {
$soundcloud = new \Soundcloud\Service(
$this->systemConfig->soundcloud->app_id,
$this->systemConfig->soundcloud->secret,
$this->systemConfig->soundcloud->redirect);
$soundcloud->setAccessToken($access_token);
try {
$response = json_decode($soundcloud->get('me'), true);
if (array_key_exists('id', $response))
return array($access_token, $response['id']);
} catch (Soundcloud\Exception\InvalidHttpResponseCodeException $e) {
$this->mlog->err($e->getMessage());
}
throw new AuthTokenInvalidException();
}
I have a few custom classes above, such as the Exceptions and the systemConfig, but I think it's verbose enough to communicate what they do.
I'm building a new project and I'm having some debate over how it needs to be developed. The big picture is to develop a consumable JavaScript widget that other internal developers can embed into their web applications. The trick is that the consumer needs to be able to tell me what AD user is currently logged into their page...and then I need to trust that the passed username is coming from the consumer and hasn't been tampered with via outside sources.
The overall solution needs to have a VERY simple set-up on the consuming side involving no compiled code changes. Also it needs to be functional across both ASP.net and PHP applications (hence my decision to go with JavaScript).
Overall, it's kind of like an Oauth solution...except the trust between domains can be intrinsic since I'll already know every user in the company trusts the host domain.
I started stubbing it out and got kind of stuck. My idea was that I would basically host a JavaScript file that the client host could embed in their page. During their page load cycle, they could init my JavaScript widget and pass it a plain text username (all I really need). Somehow I would establish an secure trust between the client host's web page, and my widget so that it would be impossible for a third-party to embed my widget into a false web page and send action commands under a user other than their own.
I hope this makes sense to someone.
I haven't really discovered an answer so to speak, but I've decided on a method:
So, I decided on a pattern where I write my JavaScript and HTML widget using the proposed jQuery UI Widget Factory. That allows the my consumer to implement the widget using simple syntax like:
<script src="widget.js"></script>
$('#someElement').myWidget({ encryptionUrl: handlerPath });
Now, you'll noticed that as part of my widget, I ask the consumer to pass a "handlerPath." The "handler" is simply an Microsoft MVC Controller which is in charge of getting the logged in user, and encrypting the call.
So the handler in my app looks something like this...
[Authorize]
public JsonpResult GetToken(string body, string title, string sender)
{
Packet token = new Packet();
try
{
// Get the widget host's public cert
string publicKey = "some.ssl.key.name.here";
// Get the consumer host's private cert
string privateKey = "this.consumers.ssl.key.name.here";
// Build a simple message object containing secure details
// Specifically, the Body will have action items (in JSON) from my widget
// The User will be generated from the consumer's backend, thus secure
Message message = new Message(){
Body = body,
Title = title,
User = System.Web.HttpContext.Current.User.Identity.Name,
EncryptionServerIP = Request.UserHostAddress,
Sender = new Uri(sender),
EncryptionTime = DateTime.Now
};
PacketEncryption encryption = new PacketEncryption();
// This class just wraps basic encryption and signing methods
token = encryption.EncryptAndSign(message, publicKey, privateKey);
token.Trust = "thisConsumerTrustName";
}
catch (Exception exception)
{
throw;
}
return this.Jsonp(token);
}
Now, I have an encrypted "token" which has been encrypted using the widget host's public key, and signed using the widget consumer's private key. This "token" is passed back to the widget via JSONP from the consuming server.
My widget then sends this "token" (still as JSONP) to it's host server. The widget hosting server has decrypting logic which looks something like this.
public Message DecryptAndVerify(Packet packet, string requestIP)
{
if (packet == null) throw new ArgumentNullException("packet");
if (requestIP == null) throw new ArgumentNullException("requestIP");
Message message = new Message();
try
{
// Decrypt using the widget host's private key
RSAEncryption decrypto = new RSAEncryption("MyPrivateKey");
// Verify the signature using the "trust's" public key
// This is important because like you'll notice, I get the trust name
// from the encrypted packet. I then maintain a "trust store" mapping
// in my web.config, or SQL server
RSAEncryption verifyo = new RSAEncryption(GetPublicKeyFromTrust(packet.Trust));
string decryptedJson = decrypto.DecryptString(packet.EncryptedData);
// Verify the signature
if (!verifyo.Verify(decryptedJson, packet.Signature))
{
Exception ex = new Exception("Secure packet was not verified. Tamper evident");
throw ex;
}
// If the message is encrypted correctly, turn it into a message object
message = decryptedJson.FromJson<Message>();
// Verify the ip
if (message.EncryptionServerIP != requestIP)
{
Exception ex = new Exception("Request IP does not match encryption IP. Tamper evident");
throw ex;
}
// Verify the time
if ((DateTime.Now - message.EncryptionTime).Seconds > 30)
{
Exception ex = new Exception("Secure packet is too old");
throw ex;
}
}
catch (Exception ex)
{
throw ex;
}
return message;
}
The idea is that the JavaScript widget determines the secure actions the end user wants to take. Then it calls back to it's host (using the handler path provided by the consumer) and requests an encrypted token. That token contains the IP address of the caller, a timestamp, the current AD username, and a bundle of actions to be completed. Once the widget receives the token, it passes it over to it's own host server at which point the server checks to make sure that it is
Signed and encrypted properly according to predefined trusts
Not older than 30 seconds
From the same IP as the initial request to the consumer's server
After I determine those checks to be valid I can act on the user's actions by creating a WindowsPrincipal identity from the string username like this:
WindowsPrincipal pFoo = new WindowsPrincipal(new WindowsIdentity("username"));
bool test = pFoo.IsInRole("some role");
All said and done, I have established a trusted request from the widget consumer, and I no longer have to prompt for authentication.
Hopefully this helps you out. It's been running in my internal environment for about a month of QA and it's it's working great so far.
Im trying to connect from PHP(Zend Framework) code to an aspx Web Service. I need to send via post a few parameters to the page( email, password). I have tried to use Zend_Http_Client, and do this:
$client = new Zend_Http_Client('https://thesiteurl.asmx/Login');
$client->setMethod(Zend_Http_Client::POST);
$client->setAuth($username, $password);
$client->setParameterPost(array('email' => 'email', 'password' => 'password'));
$response = $client->request();
$this->view->response = $response;
where $username, $password are the username and password I use to log in to the web service(it has a pop-up window that asks me for username and password).
This code gives me the unauthorized page. So im asking where am I using the site username and password wrong? How can I use them?
edit:
The Auth is auth-basic.
Edit2:
I talked to the owner of the web service he says that everything is UTF-8 is this a problem, isnt it is a default? If not how do i do that?
You could check if a referer-header is needed, or it might be that it also needs a cross-site request forgery number. Simply dump the request that is made by your browser when you login and dump the request that your script is generating, compare those and it should work out.
For the browser-request dump you could use livehttpheaders plugin for firefox.
Depends on what that pop up box really is.
You probably need to study the HTTP Authentication. Currently, Zend_Http_Client only supports basic HTTP authentication. This feature is utilized using the setAuth() method, or by specifying a username and a password in the URI. The setAuth() method takes 3 parameters: The user name, the password and an optional authentication type parameter. As mentioned, currently only basic authentication is supported (digest authentication support is planned).
// Using basic authentication
$client->setAuth('shahar', 'myPassword!', Zend_Http_Client::AUTH_BASIC);
// Since basic auth is default, you can just do this:
$client->setAuth('shahar', 'myPassword!');
// You can also specify username and password in the URI
$client->setUri('http://christer:secret#example.com');
Source.
If this is not an HTTP auth and is somothing else, try to use cURL, wget or linx to see exactly what is happening on the page and now you can simulate it using Zend_Http_Client.
Sometimes you have to send cookies, execute some Js or follow some redirects. Zend_Http_client can do all this things.
have you tried this?
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Socket',
'ssltransport' => 'tls'
);
$client = new Zend_Http_Client('https://thesiteurl.asmx/Login', $config);
$client->setAuth('shahar', 'myPassword!', Zend_Http_Client::AUTH_BASIC);
also I am confused, is this popup a http basic auth, or something that is self designed?
since for basic auth you normally wouldn't send any post params...
the real URL of the site would help very much for finding the solution...
If you can access the servis using browser, use firebug to check the request and response. There might be some other parameters involved, eg cookie.
The best way to tackle these things is by just using the packet sniffer (tcpdump, ethereal, ...) to see what's happening on the line. Then compare the request/response you observe in a working scenario (e.g. from your browser) to the request/reponse which is not working.
This will very quickly reveal the precise difference at the HTTP level. Using this information you can either find out what to fix in your handling of Zend_Http_Client, or find out that Zend_Http_Client doesn't support a particular feature or authentication scheme.