Laravel Passport; using OAuth2 for SSO with Freshdesk - laravel

I am trying to set up SSO from my Laravel 8.13 site to my related Freshdesk support portal.
What I want is for a user, who is logged into my site, then to be able to click a button and get seamlessly signed into my Freshdesk support portal so they can view the non-public documentation there and raise tickets if required.
Using Laravel Passport 10.1 I can create a token (tested using Postman) but get an error from Freshdesk when trying to authenticate.
An error occurred while attempting to retrieve the userinfo resource: could not extract response: no
suitable httpmessageconverter found for response type [java.util.map<java.lang.string,
java.lang.object>] and content type [text/html;charset=utf-8]
I have not used OAuth before and am having issues. It may of course be that my understanding of OAuth is just completely wrong but I am finding available documentation on Laravel Passport / Freshdesk OAuth connectivity hard to come by.
I have been through as many related SO questions as I have found but nothing so far seems to exactly fit my issue.
I have also got open tickets with Freshdesk and have had an online support session with a Freshdesk support member but they told me the issue was on my side and they couldn't help further.
I would have thought the client type to use was a Personal Access Client but I have tried that as well as a Password Grant Client and get the same message (as above) for both client types.
As far as the "User info URL*" field on Freshdesk goes,
I have tried
http://testsite.ngrok.io/oauth/tokens
and
http://testsite.ngrok.io/oauth/personal-access-tokens
and
http://testsite.ngrok.io/api/user
But no luck - same message regarding not finding userinfo resource as above.
If I browse directly to
http://testsite.ngrok.io/oauth/personal-access-tokens
I get the following returned:
[{"id":"e595f342722c1045e061f2f026fa7f07181b3d5c69016e9999c5640f1e65928ff6fe2621565ff666c5",
"user_id":43128,"client_id":7,"name":null,"scopes":"openid","email","profile"],"revoked":false,
"created_at":"2021-01-26 10:16:12","updated_at":"2021-01-26 10:16:12",
"expires_at":"2022-01-26T10:16:12.000000Z","client":
{"id":7,"user_id":null,"name":"freshworksPersonalAccessClient",
"provider":null,
"redirect":"https:\/\/testsite.freshworks.com\/sp\/OAUTH\/27402945223480041\/callback",
"personal_access_client":true,"password_client":false,"revoked":false,
"created_at":"2021-01-19T23:19:39.000000Z","updated_at":"2021-01-19T23:19:39.000000Z"}}]
so something is returned but I am not sure if that is in any way near what Freshdesk is looking for. The support documentation for Freshdesk states :
But I do not know where to create that info or in what format it needs to be sent to Freshdesk.
I have looked at this question and believe that (even though it is for older versions) there might be something in the code for "getUserEntityByUserCredentials" in the UserRepository.php file but I have put logger calls in that function and it doesn't seem to be called.
Any assistance would be absolutely great. If any further information is required please let me know.
Although I would prefer to keep it within the Laravel ecosystem, I am also open to any other way to set up SSO to Freshdesk without using a third party Identity Provider like ADFS, OneLogin, Okta, Azure and suchlike. I just need to get this done.

Solved it. Basically my issue was the format and content returned by the User info URL.
I set up a route for
/userinfo
to a function in a TestController. In that function I decoded the Bearer token to get the user_id and then used that to retrieve the user details.
Then I created an array and response as below:
$thisDecodedUser = User::query()->findOrFail($thisDecodedUserId);
if ($thisDecodedUser) {
$thisDecodedUserFirstName = $thisDecodedUser->first_name;
$thisDecodedUserLastName = $thisDecodedUser->last_name;
$thisDecodedUserEmail = $thisDecodedUser->email;
}
$user_info = array();
$user_info['sub'] = "$thisDecodedUserId";
$user_info['id'] = "$thisDecodedUserId";
$user_info['email'] = "$thisDecodedUserEmail";
$user_info['.id'] = "$thisDecodedUserId";
$user_info['.email'] = "$thisDecodedUserEmail";
$user_info['email_verified'] = "true";
return response(json_encode($user_info))
->withHeaders([
'Content-Type' => 'application/json',
]);
The code needs refactoring but at least it works for now.

Thank you for pointing me in the right direction in this answer : https://stackoverflow.com/a/65929987/920598
Even if the array you use contains unused keys.
Actually, the available fields and their format are described here https://support.freshdesk.com/en/support/solutions/articles/50000002088-configuring-custom-sso-policies-under-org
For example, if you want to sync the firstname, the lastname and the language, here's the keys you need to set :
<?php
$user_info = [
'sub' => (string)$user->id,
'unique_id' => (string)$user->id,
'email' => $user->email,
'FirstName' => (string)$user->firstname,
'LastName' => (string)$user->lastname,
'language' => $user->default_ln === 1 ? 'fr' : 'en'
];

Related

Using Laravel Test 7 and Laravel Passport 9.3 with Personal Access Client gives exception "Trying to get property 'id' of non-object"

I am designing a custom authentication scheme (based on public keys) alongside a stateless API, and decided Passport would fulfill the need for post-authentication requests.
Assuming the authentication succeeds, and the user is authenticated, they would receive a Personal Access Token, and use the token for all further requests. The trouble I'm experiencing (still after much searching through various forums and Stack Overflow) is that when using Laravel's built in testing suite, on the createToken() method, it generates an (admittedly common) exception:
"ErrorException : Trying to get property 'id' of non-object".
I am able to manually create a user through Tinker, and create a token through Tinker. However I'm experiencing problems when attempting to automate this process after authenticating.
Here is the relevant code snippet post-authentication:
Auth::login($user);
$user = Auth::user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
"access_token" => $tokenResult->accessToken,
"token_type" => "Bearer",
"expires_at" => Carbon::parse(
$tokenResult->token->expires_at)->toDateTimeString()
],
200);
I've manually called Auth::login on the user, to ensure the user is logged in, and Auth::user() returns the user (not null). Upon executing the third line of code, the exception is thrown with the following mini stack-trace (I can provide a full stack-trace if requested).
laravel\passport\src\PersonalAccessTokenFactory.php:100
laravel\passport\src\PersonalAccessTokenFactory.php:71
laravel\passport\src\HasApiTokens.php:67
app\Http\Controllers\Auth\LoginController.php:97
laravel\framework\src\Illuminate\Routing\Controller.php:54
laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php:45
From running this through debug a few times- even though the class is called and loaded, and it appears the Client is found through ControllerDispatcher -> Client::find(id) and found in ClientRepository, when it gets to PersonalAccessTokenFactory, the $client passed in is null (which explains why the $client->id can't be found, though I have no idea why the $client is null at this point).
protected function createRequest($client, $userId, array $scopes)
{
$secret = Passport::$hashesClientSecrets ? Passport::$personalAccessClientSecret : $client->secret;
return (new ServerRequest)->withParsedBody([
'grant_type' => 'personal_access',
'client_id' => $client->id,
...
}
Things I have done/tried with some guidance from the documentation and other posts:
Manually created a user in Tinker, and created the token through Tinker- this does work.
Ensured the user is logged in before attempting to generate token.
passport:install (and adding the --force option)
Ensured Personal Access Client is generated with passport:client --personal
Ensured the AuthServiceProvider::boot() contains the ClientID and Client Secret (in the .env).
migrate:refresh followed by passport:install --force
Complete removal of Passport, removing all files, keys, migrations, and DB entries, followed with a migrate:refresh and reinstallation of Passport, along with generating an additional personal access client (even though one is generated during passport:install).
I'm not sure where else to look/what else to try at this point, so any help or guidance would be much appreciated!
I eventually discovered the solution. The problem is multi-layered, in part having to do with outdated Laravel documentation in regards to testing and Passport Personal Access Clients.
The first part of the problem had to do with using the trait RefreshDatabase on my unit test. Since this creates a mock database with empty datasets, although the clients themselves exist in the real database and the .env file, when the test is run, the test does not see those clients as existing in the mock database. To solve this problem, you must create a client in the setup function before the test is run.
public function setUp() : void
{
parent::setUp();
$this->createClient(); //Private method->Full code below
}
This solves the issue about having a null client during testing, but starting in Laravel 7, Laravel added a requirement for Personal Access Clients that the id and the client secret has to be kept inside the .env file. When running the test, the test will see the actual client id and secret in the .env, and fail to validate these with the client that was created and stored in the mock database, returning another exception: "Client Authentication Failed".
The solution to this problem is to create a .env.testing file in your main project directory, copying your .env file contents to it and ensuring that the keys below exist with values for either your main created Personal Access Client, or copying the secret from a client generated just for testing (I would advise the latter).
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=1
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=unhashed-client-secret-value
Then using the code below, make sure the $clientSecret value is the same as the key value in your .env.testing file.
private function createClient() : void
{
$clientRepository = new ClientRepository();
$client = $clientRepository->createPersonalAccessClient(
null, 'Test Personal Access Client', 'http://localhost'
);
DB::table('oauth_personal_access_clients')->insert([
'client_id' => $client->id,
'created_at' => new DateTime,
'updated_at' => new DateTime,
]);
$clientSecret = 'unhashed-client-secret-value';
$client->setSecretAttribute($clientSecret);
$client->save();
}
This will create a new client, set the attribute secret to the value in the variable and update the mock database secret to contain the same value. Hopefully this helps anyone with the same issue.
Another way to prevent copy/paste source code is to just call artisan command in the setup method.
public function setUp() {
parent::setUp();
$this->artisan('passport:install');
}
original here
Just use the facade
public function setUp() {
parent::setUp();
Artisan::call('passport:install');}

Trying to stop Google Directory API push notifications with a client returns 404

Using the documentation at https://developers.google.com/admin-sdk/directory/v1/guides/push#creating-notification-channels I subscribed to a notification using something like:
service = build('admin', 'directory_v1', credentials=credentials)
watch_data = {
'id': str(uuid.uuid1()),
'type': 'web_hook',
'address': 'https://example.appspot.com/push/user',
'payload': True,
}
subscription = service.users().watch(domain=domain, event='update', body=watch_data).execute()
# 'subscription' is stored
I got a proper reply and everything seem fine to that point.
Until I try to stop the notification with the following code:
# 'subscription' is retrieved from the storage
service = build('admin', 'directory_v1', credentials=credentials)
stop_data = {
'id': subscription.id,
'resourceId': subscription.resource_id
}
request = service.channels().stop(body=stop_data)
request.execute()
This raises an 'HttpError' 404 exception:
Response: <HttpError 404 when requesting https://www.googleapis.com/admin/directory/v1/admin/directory_v1/channels/stop? returned "Not Found">
Interestingly, using the same parameters (known good 'id' and 'resourceId' from the same user), the API explorer gadget at https://developers.google.com/admin-sdk/directory/v1/reference/channels/stop fails in the same way.
I've also been unable to find this endpoint in the full blown API explorer.
I believe that the discovery somewhat misbehaves.
The URI built by the client is: 'https://www.googleapis.com/admin/directory/v1/admin/directory_v1/channels/stop'
whereas the documentation states it should be:
'https://www.googleapis.com/admin/directory/v1/channels/stop'.
Could this be a bug in the API?
I'll try to make a "manual" authenticated request ASAP to check this hypothesis.
Edit 2016-11-09:
Tried a manual request using the following code:
# 'subscription' is retrieved from the storage
stop_data = {
'id': subscription.id,
'resourceId': subscription.resource_id
}
http = httplib2.Http()
http = credentials.authorize(http)
url = 'https://www.googleapis.com/admin/directory/v1/channels/stop'
method = 'POST'
response, content = http.request(url, method, body=json.dumps(stop_data),
headers={'content-type': 'application/json'})
I still get a 404 as a result. So I guess that the problem is not the endpoint URI.
If someone from Google reads this, can you please look into it?
It's not super critical but I'd like to not have dangling notification subscriptions.
Edit 2 2016-11-09:
Thanks to #Mr.Rebot for pointing out the reports API bug report.
Upon closer inspection, the problem here is exactly the same.
Using the manual request code above but adjusting the URI with an underscore, I'm finally able to make a successful request (returns 204).
url = 'https://www.googleapis.com/admin/directory_v1/channels/stop'
So there's definitely a bug somewhere and the following documentation pages have the wrong endpoint URI:
https://developers.google.com/admin-sdk/directory/v1/guides/push#stopping-notifications
https://developers.google.com/admin-sdk/directory/v1/reference/channels/stop
Also found this related post: Google Admin SDK Channel Stop endpoint is broken in client libraries
To those that wonders in the Google Docs hell for the past two years, and counting.
The wrong/right URL is:
https://www.googleapis.com/admin/reports_v1/channels/stop
And the Scope to use this URL is:
https://www.googleapis.com/auth/admin.reports.audit.readonly
I hope this helps someone :)

Requesting An Access Token from Google API Returns 302

I'm trying to get an access token from Google API in my Ruby on Rails app, as part of an overall goal of setting up a raketask. I am able to get an Auth Code fine, but when I make a post request to get an access token, I am getting a 302 error. I'll describe my current code first, and afterward list how I've tried to solve the problem so far.
Current code:
#users_controller
def auth_access
client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_endpoint_uri => 'https://accounts.google.com/o/oauth2/token',
:client_id => ENV['OAUTH_CLIENT_ID'],
:client_secret => ENV['OAUTH_CLIENT_SECRET'],
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:redirect_uri => 'http://localhost:3000/google/auth_callback'
)
redirect_to client.authorization_uri.to_s
end
This part works fine so far. It redirects to the consent page, and when the user agrees it then redirects them to the page with the auth code in the url parameters. Next I take that auth code and try to make a POST request to API for an access token:
#users_controller
def auth_callback
http = Net::HTTP.new('accounts.google.com')
path = '/o/oauth2/token'
data = "code=#{params['code']}&client_id=#{ENV['OAUTH_CLIENT_ID']}&client_secret=#{ENV['OAUTH_CLIENT_SECRET']}&redirect_uri=http://localhost:3000/auth_final&grant_type=authorization_code"
response = http.post(path, data)
end
This when I run into a problem. The Google API returns a 302, and includes a message saying something akin to "we moved to 'https://accounts.google.com/o/oauth2/token'".
Here's how I've tried to fix the problem so far:
I assumed that the problem was that the http.post method is making a call to an http and not https.
I've tried including
http.use_ssl = true
http.ssl_version = :SSLv3
This returns the error "SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: wrong version number".
I can take a guess at what this means, but I am still unsure of what the actual problem is and how to solve it. Googling the error message has not been a help.
In a similar vein, I tried using gems to make the https call for me, in particular HTTParty and Typheous, although I was not able to make any progress with them (and am still not even sure that it's an http/https problem).
I've tried using the Signet-Rails gem. This was the most productive method by far, making a successful API call and returning the information. However, it either wasn't saving the refresh token or I cannot find where it is being saved. As I need access to that token to run the rake tasks, I gave up on Signet-Rails.
I tried using Legato, and was constantly running into various problems. Overall, Legato left me with the impression that it did not integrate getting the auth code, consent and tokens into the app, instead requiring the developer to set those up in advance outside of the app's scope. I want to be able to set up the auth code as part of the app. If I am understanding Legato properly, then it is not the gem I need.
I've also tried other various odds and ends but to no avail. The above solutions were the tactics I kept coming back to. Primarily I'm looking for an answer to what is going wrong in my code, and what is the best avenue to fix it (and if I was going down the right track with any of my attempted solutions above, which one?)
Thanks for taking the time to read this and answer!
(on a complete sidenote, those last three list items should be 2, 3, 4, but the stackoverflow text editor thinks it knows better than me...)
Specify the port:
http = Net::HTTP.new('accounts.google.com', 443)
Source: SSL Error on HTTP POST (Unknown Protocol)

codeigniter php native sessions without using cookies or URL session id, but matching browserfingerprints in database

Because of european privacy law being harsly applied in the Netherlands and to keep my company's site user friendly without nagging the users with questions if it's okay to store a cookie on their computer that allows me to access their client data.
What I need is a way to "overwrite" the native php sessions class so that at the point where the native class requests the cookie that stores the phpsessid, that I can place my own code there that checks the browsers fingerprint and matches that to a session id which I can use to return the normal working of the native class.
My idea is:
table sess_fingerprints
Fields: fingerprint - phpsessid
function getsessionid()
{
$result = $this->db->query("SELECT phpsessid
FROM `sessiondatabase`.`sess_fingerprints`
WHERE `sess_fingerprints`.`fingerprint` = '$userfingerprint'");
if($result->num_rows() != 0)
{
return $result->row->phpsessid;
}
}
and at that point the native php session code just works as it would normally do.
So, my question is: is it possible to overwrite only the "cookie" part of the phpsession class? if so, how? because I haven't found that yet.
I'm aware of being able to pass along the session variable via urls etc, but that's not secure enough for my web applications.
PHP provides support for custom session handlers:
http://php.net/manual/en/session.customhandler.php
I think I have found the solution to my problem.
I'm going to override the functions related to cookies by using http://php.net/manual/en/function.override-function.php
Thank you all for thinking along.

Why does Google's Custom Search API say that I'm missing an access token when using the Ruby client?

I'm trying to use Google's Custom Search API through the Google API Ruby client. I have setup my API key through the Google API console, and have also created my CSE. Based on the documentation, it seems that, as long as I provide an API key (which I am doing), I shouldn't need an OAuth2 authentication token to call the list method. However, when I try to execute the code below, I get the following error:
ArgumentError: Missing access token.
What am I missing? Here's my code:
# create client
client = Google::APIClient.new
# Fetch discovery doc
search = client.discovered_api('custom search')
# Call list method
response = client.execute(
search.cse.list, 'key' => '<my API key>', 'cx' => '<my CSE id>', 'alt' => 'json', 'q' => 'hello world'
)
I believe this is in fact a bug in the client (it's in alpha). After fiddling with it a little more, I've found a workaround:
just after creating the client object, assign it a "dummy" access token:
client.authorization.access_token = '123'
then you can call the search.cse.list method without getting the 'ArgumentError: Missing access token.' error.
If you're just after using Google CSE with ruby, try google-cse. I just built the gem, although I've been using it for a while privately. Much easier to work with than the alpha client
I found out that adding client.retries = 3 to my code solves this problem.
With the current version of the gem (0.7.1), you need to set the authorization to nil in addition to setting the key:
require 'google/api_client'
client = Google::APIClient.new
client.key = ENV['GOOGLE_API_KEY']
client.authorization = nil
client.execute ...

Resources