Access tokens? - access-token

I am developing an app in PHP hosted on Heroku, and my biggest problem is not getting access tokens for a user to get my app to fully work. The app works perfectly for me (as I am an admin), but other people who arent associated with the app cannot get the app to display anything. I also tried using test users to see if it would work, but still no luck. Im pretty sure it has to do with access tokens and the app not having permission to do its thing. How and where do I fix this?

for user access_token i use, where the number is the application id.
if($_SESSION['fb_135669679827333_access_token']){
$access_token = $_SESSION['fb_135669679827333_access_token'];
}
for application access token i use cURL. the return results are like access_token=xxxxxxxxxx
use like - /anotherfeed/feed?$app_access_token
$app_access_token = GetCH();
function GetCH(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=SECRET_KEY&grant_type=client_credentials");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
if(substr($url,0,8)=='https://'){
// The following ensures SSL always works. A little detail:
// SSL does two things at once:
// 1. it encrypts communication
// 2. it ensures the target party is who it claims to be.
// In short, if the following code is allowed, CURL won't check if the
// certificate is known and valid, however, it still encrypts communication.
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
}
$sendCH = curl_exec($ch);
curl_close($ch);
return $sendCH;
};

Related

How to prevent multiple login to the same account in ASP.NET Core

I'm using ASP.NET Core 6 Identity for login system. I want to prevent multiple login to the same account.
My Identity settings are:
//For custom Identity
string connection = configuration.GetConnectionString("DefaultConnection");
builder.Services.AddIdentity<AppUser, AppRole>(options =>
{
options.User.RequireUniqueEmail = false;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = false;
options.Password.RequiredUniqueChars = 0;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 6;
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultProvider;
}).AddEntityFrameworkStores<IdentityAppContext>().AddDefaultTokenProviders();
I searched some similar questions but none of them could help me to implement this feature in ASP.NET Core 6.
Please guide me.
What is the Use Case for denying access while logged in?
"When someone logged in, no body can log in to that account until he closes the browser or logs out manually"
That would require logic like:
On Login, throw error if tokenHasBeenIssued, by querying the server db.
On Login, if no server token for user, createToken.
On Logout, a clean db, removeUserToken
but, when someone closes their browser there is no message sent to the server, so you'd never clear the token, so you'd get one login granted and then they would be logged out forever.
Maybe this scenario is fixable with a hack of a 'Timed cron job to clear all old tokens'?
I would suggest implement two factor authentication or even delegate your auth needs to third party provider, eg Auth0 or Azure AD, etc.
If you mean to stay signed in, you need to implement a token(for example, JWT Token) and use User ID or username directly without logging in again.

Google Developer API service account authentication requests User Account

I am trying to authenticate to Google API services from a web server to check Customer subscription statuses. I am using PHP on my server. I could figure out how to get the access token from the server with the service account I have generated on the API console.
It works fine, but just after it pops up an authentication screen and once I log in with my user account. I was reading the documentation and it should work without asking me to log in, but I cannot figure out what is the problem.
My code is like this
$clientID="{my service account email address}.apps.googleusercontent.com";
$clientSecret="{my service account secret code}"; //Actually this is not used by the call
$scope="https://www.googleapis.com/auth/androidpublisher";
$ch = curl_init();
$input_fields =
'&client_id='.$clientID.
'&response_type=code'.
'&type=service_account'.
'&scope='. $scope .
'&redirect_uri={my Redirect URI, set on the API Console}';
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/auth");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $input_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
Once this code is running, the authentication screen comes up, I need to grant access for website to access the API on behalf of my user account. After that I get the access token and the scope in a json using the Redirect URI page.
How can I avoid to be asked for my user account and just get the access token automatically?
Thanks for helping me out here.

chatbot: how to validate incoming requests from google hangouts

We've put together a google hangouts chat bot to provide some convenient functionality for our team. The bot is of the 'bot URL' variety, meaning that hangouts sends requests to an app endpoint and our app responds appropriately. At the moment, we're struggling to now validate the incoming requests from google. Each request has a bearer token in the Authentication header, but that JWT token does not validate. Both the php client library [https://github.com/googleapis/google-api-php-client] and the online validator [https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=] return the error 'invalid signature'
The google client php library's Google_AccessToken_Verify class has a verifyIdToken method which we use as described here in this example [https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/auth/src/auth_cloud_explicit.php]. We pass the path of our service account key file and the project ID into the google client constructor. Then we pass the incoming request's bearer token into the verifyIdToken method.
use Google_Client;
// inside a laravel controller with $request in scope
$bearer_token = $request->bearerToken();
$keyPath = FILE_LOCATION
$client = new Google_Client([
'keyFilePath' => $keyPath,
'projectId' => GCP_CLIENT_ID
]);
$payload = $client->verifyIdToken($bearer_token);
if(!empty($payload)){
return $this->call(ParseGoogleChatRequest::class, [$request]);
}else{
\Log::debug('bad token');
}
I expect the google client library to be able to validate a google JWT. This github issue [https://github.com/firebase/php-jwt/issues/175] reflects our experience implementing this approach. I would like to get some general guidance on which approach we should be using.
I figured out an acceptable solution with the help of another SO question. The google client library was already importing firebase/php-jwt, so I followed along the same lines as Jed from the question I linked to. Extracting the KID from the token, I used it to identify the correct public key from this url. Then I instantiated the php-jwt library and called the decode method on it, passing the required arguments. The decode method also verifies the signature and returns the components of the JWT on success.

Can't access IBM Tone Analyzer API?

I'm trying to use the Tone Analyzer API in a Laravel application. No matter what I try, I always get the same response of {"code":401, "error": "Unauthorized"}. I suspect my issue is that I can't figure out how to pass in the API key, but the official documentation is no help whatsoever because it only contains instructions for using cURL in the command line. My code currently looks like this (though I have tried many many other iterations. If anyone needs me to I can post all the other unsuccessful attempts as well):
$response = Curl::to('https://gateway-wdc.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false')
->withOption('HTTPHEADER', array(
'Content-Type: application/json',
'apikey: REDACTED'))
->withData(array('text' => $text))
->asJson()
->post();
I am running Laravel 5.8 and using Ixudra's cURL library. I would prefer if answers made use of this library too but honestly at this point I'm ready to give up and use vanilla PHP anyway so any answers are appreciated.
Ninja edit: I know the problem is not my account / API key, because I have tried to access the API through the command line and it worked just as expected. The issue only arises when trying to access it from Laravel.
IBM Watson Services uses HTTP Header Authentication in Basic format. Therefore, using curl in the terminal, you should pass the-u or --user flag in the format user:password, or you can also send the Authentication Http Header in pattern: Basic user:password.
By adjusting your code for this second form, you can do it as follows:
$response = Curl::to('https://gateway-wdc.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false')
->withHeader('Content-Type: application/json')
->withHeader('Authorization: Basic apikey:YOUR_TOKEN_HERE')
->withData(array('text' => $text))
->asJson()
->post();
Replace YOUR_TOKEN_HERE by your Tone Analyzer API access token.
https://developer.mozilla.org/docs/Web/HTTP/Authentication
https://www.ibm.com/support/knowledgecenter/en/SSGMCP_5.3.0/com.ibm.cics.ts.internet.doc/topics/dfhtl2a.html
Hope this helps!
It's 401 status code which uses for unauthorized access, you need to login first before accessing the API.
I check the docs for this and here is the link, for login to the api before using it
tone-analyzer#authentication
With some service instances, you authenticate to the API by using IAM. You can pass either a bearer token in an Authorization header or an API key. Tokens support authenticated requests without embedding service credentials in every call. API keys use basic authentication.

Adldap 2 can connect and find a user but cannot authenticate

Question: why can I not authenticate a known registered user through Adldap despite being able to access information about the user using Adldap on laravel 5.2?
I am attempting to use Adldap on laravel 5.2 to authenticate users at a university. I have successfully managed to connect to the ldap server with the admin credentials and can even retrieve information about the user.
`
namespace App\Http\Controllers;
use Auth;
use Input;
use Adldap;
class AuthController extends Controller
{
public function authenticate()
{
$username = Input::get('username');
$password = Input::get('password');
$authentic = Adldap::authenticate($username,$password);
$userData = Adldap::users()->find($username);
var_dump( $authentic );
dd( $userData );
}
}
`
when I try to log in, dumping $authentic gives me false despite having the correct password (I dumped it as well to check). However, with the same username if I dump $userData i get a massive array of (correct) user information. Using my username, if I open the $userData object up I can see what email groups i'm in, my campus mailing address, my work title etc.
Dumped variables. I am very new to using ldap and am not quite sure how everything works. Also, its probably worth noting that despite me being the guy doing the setup and such I do not have much access to the servers. Everything is on an as needed basis.
One though was that the ldap server took care of any password hashing on that end. However, since i'm getting connected but the authentication fails could it be that I need to hash the password on my end? Please explain any solutions in detail. As an Ag engineer none of this is exactly my field but sometimes branching out is a necessity.
There are no errors. I'm on wamp and in logs/php_error (I assume this is the equivalent local version of /var/log/debug). Additionally, apache_error shows no problems.
You better check the messages created in /var/log/debug while trying to log in. Please add these messages to this post.
There was no "error" on my end. The Ldap server was simply configured to accept the users full email address and not their short id as I was using.

Resources