Can User Create or Change Firebase Auth.uid? - python

I'm going to use Firebase in my Android project and i want to authenticate the user with signInWithCustomToken function.
I'll generate the token from my Admin SDK(Python) and return it to the user and the user will authenticate with that token.
My question is;
1 -> That token i generated with a key can be generated by only me? I mean is it unique to me?
uid = 'some-uid'
custom_token = auth.create_custom_token(uid)
Can someone create the same token as mine if he uses the same uid or is it always unique?
2 -> Can someone set fireabase.auth.uid variable manually, without using firebase.authenticate function?
I mean if someone gets the auth.uid but not the token, can he set that auth.uid in client to auth variable?
Thanks for the informations and answers...

1 - The custom token could only be duplicated if someone gains access to your serviceCredentials file, meaning they'd have full access to read/write your Firebase contents. If you create a token with the same UID from a different Firebase project, the tokens won't match.
2 - Someone may attempt to set the auth.uid variable manually, however, this is useless without the auth token its-self, which enables read/write on the database (depending on your Firebase security rules). Firebase documentation states that they will generate the auth token, and once again this cannot be done without having your serviceCredentials file.

Related

Storing access and refresh token in python self.sessions doesn't work

I am currently developing integration for users and groups through Azure AD. I have set up everything to retrieve an access and refresh token upon login, I am only having trouble storing both of them in the sessions. I am assigning the tokens to a session and trying to retrieve them as shown below.
self.session["access_token"] = json.dumps(access_token)
self.session["refresh_token"] = json.dumps(refresh_token)
then I am fetching both tokens on another page, using
access_token = json.loads(self.session.get('access_token'))
refresh_token = json.loads(self.session.get('refresh_token'))
I can only for some reason get the access_token inside the other page, the refresh token is always None. For reference I am using the BaseHandler module on both pages.I was thinking of storing both in the database being a solution, but I want to know if it is possible to configure it in some way to work with self.session. Any help is greatly appreciated!

Is it possible to store authentication token in a separate file?

I am building a command line tool using python that interfaces with an RESTful api. The API uses oauth2 for authentication. Rather than asking for access_token every time user runs the python tool. Can I store the access_token in some way so that I can use it till its lifespan? If it is then how safe it is.
You can store the access token in a file on your user's desktop.
You can do so using a storage. Assuming you use oauth2client:
# Reading credentials
store = oauth2client.file.Storage(cred_path)
credentials = store.get()
# Writing credentials
creds = client.AccessTokenCredentials(access_token, user_agent)
creds.access_token = access_token
creds.refresh_token = refresh_token
creds.client_id = client_id
creds.client_secret = client_secret
# For some reason it does not save all the credentials,
# so write them to a json file manually instead
with open(credential_path, "w") as f:
f.write(creds.to_json)
In terms of security, I would not see much of a threat here as these access tokens will be on a user's desktop. If someone wants to get their access token, they would need to have read access to that file for that time frame. However, if they can already do that, they most likely also can use your script to send them a copy of the user's access token every time it is authenticated. But take my word lightly as I'm not a professional in that area. See information security stack exchange.
A post in information security stack exchange did talk about this:
these tokens give access to some fairly privileged information about your users.
However, the question was addressed to a database instead.
In conclusion, you can keep it in a file. (But take my word with a grain of salt)
Do you want to store it on the service side or locally?
Since your tool interfaces RESTful API, which is stateless, meaning that no information is stored between different requests to API, you actually need to provide access token every time your client accesses any of the REST endpoints. I am maybe missing some of the details in your design, but access tokens should be used only for authorization, since your user is already authenticated if he has a token. This is why tokens are valid only for a certain amount of time, usually 1 hour.
So you need to provide a state either by using cookie (web interface) or storing the token locally (Which is what you meant). However, you should trigger the entire oauth flow every time a user logs in to your client (authenticating user and providing a new auth token) otherwise you are not utilizing the benefits of oauth.

Python Simple Salesforce

I am trying to use simple_salesforce to query salesforce data with Python. I am using my username and password, which I am 100% sure is correct. I got the org ID from logging into Salesforce and looking at my company profile. It's only a 15-digit ID. I am specifically using an orgID to avoid using a security token as I don't know what it is. What am I doing wrong?
Code:
from simple_salesforce import Salesforce
sf = Salesforce(instance_url='https://na1.salesforce.com', session_id='')
sf = Salesforce(password='password', username='email', organizationId='15 digit org id')
Output:
File "C:\Python27\lib\site-packages\simple_salesforce\api.py", line 100, in __init__
proxies=self.proxies)
File "C:\Python27\lib\site-packages\simple_salesforce\login.py", line 124, in SalesforceLogin
code=except_code, message=except_msg))
simple_salesforce.login.SalesforceAuthenticationFailed: INVALID_LOGIN: Invalid username, password, security token; or user locked out.
I wrote most of simple-salesforce (although not the organizationId part, as I don't have an IP-whitelisted account to test against)
The standard/vanilla/regular/99% of users should use version is the simple username, password, security_token method.
So something like this
from simple_salesforce import Salesforce
sf = Salesforce(username='nick#nickcatalano.com', password='nickspassword', security_token='tokenemailedtonick')
By far the most confusing part is the security_token part (and was the part I got snagged with.) It turns out the Security Token is emailed to you after a successful password reset. So if you go into your salesforce account and reset your password, I believe you'll end up with an email with the subject salesforce.com security token confirmation which will contain a Security Token in the email. That's your security_token.
To be honest, the security_token kwarg is more a convenience than anything. In the normal email/password/token flow that most users rely on what is actually being sent is email as the login and {password}{security_token} as the password. I believe you could concat that yourself and just pass in a email and password kwarg if you want, but I figured forcing people to concat the password and token themselves would get go against the simple part of simple-salesforce
There is a way to log in with simple-salesforce with only a username and password. No security token required:
from simple_salesforce import Salesforce, SalesforceLogin
session_id, instance = SalesforceLogin(username='<user>', password='<pass>')
sf = Salesforce(instance=instance, session_id=session_id)
# Logged in! Now perform API actions, SOQL queries, etc.
sf.query_all('<soql>')
Explanation
All examples using simple-salesforce begin with a call to the Salesforce constructor to log in. This constructor accepts either an existing session ID, or authentication credentials to log in and make a new session. When logging in, it calls the lower-level SalesforceLogin function to do the real work, but interestingly SalesforceLogin does not enforce the same constraints on its arguments—it issues the correct SOAP call to log in with just a username and password, without requiring a token or organization ID.
Using this trick, we call SalesforceLogin directly, obtain the new session ID, then pass it directly into the Salesforce constructor. From that point on, we are able to make authenticated API requests.
Note
The version of simple-salesforce on PyPI (i.e. pip install simple-salesforce) is very outdated with the simple-salesforce GitHub repository. The latest version supports additional login parameters like domain for login with custom domains. To get the latest version, use
pip install --upgrade https://github.com/simple-salesforce/simple-salesforce/archive/master.zip
(Pip-installing from zip is faster than using git+ssh:// or git+https://, as noted in this answer.)
Edit
How will resetting my password show me what the token is?
It just will. If user has ever before requested the security token (which is sent to you via email - so you need to have access to the email address associated with your user) - every subsequent password reset will result with new token being generated and emailed to you. On top of that, once you're logged in to the system (to the web version, not via API) you will have an option to reset your token (and again, this will send you an email).
It's like you haven't read or tried anything we have written!
Looking for an answer drawing from credible and/or official sources.
https://help.salesforce.com/htviewhelpdoc?id=user_security_token.htm
https://help.salesforce.com/HTViewSolution?id=000004502
https://help.salesforce.com/HTViewSolution?id=000003783
And from the library's documentation:
https://github.com/neworganizing/simple-salesforce
To login using IP-whitelist Organization ID method, simply use your
Salesforce username, password and organizationId
This. If your IP address is whitelisted - you don't need the token. If it isn't - you NEED to generate the token. Period.
Original answer
I'm not familiar with that Python library but... Go to Salesforce -> Setup -> My personal infromation and check login history. if it contains stuff like "failed: security token required" then you're screwed and you will have to use the security token.
I'm not aware of any bypass that uses org id (I've connected via API from PHP, Java, C#... so I'd be very surprised if that Python library had some magical way to bypass it. You probably are used to passing a session id that assumes you're already authenticated and have a valid session.
Another option would be to check your IP and add it to trusted IP ranges (it's an option in the setup). It's useful when for example whole office has same static IP; less useful if you're working from home.
If that's also a no-go - you might want to look for libraries that use OAuth2 instead of regular SOAP API to authenticate.
Although this is kinda late, somebody searching for this very same issue may be helped as to what I did.
I struggled by adding the company ID as well, but the problem here is, unless you're a self-service user, the company ID can be blank.
sf = Salesforce(password='password', username='email', organizationId='')
As other users mentioned, make sure you're using IP-White listing or it will not work.
A security token is an automatically generated key that you must add to the end of your password in order to log into Salesforce from an untrusted network. For example, if your password is mypassword, and your security token is XXXXXXXXXX, then you must enter mypasswordXXXXXXXXXX to log in. Security tokens are required whether you log in via the API or a desktop client such as Connect for Outlook, Connect Offline, Connect for Office, Connect for Lotus Notes, or the Data Loader.
To reset your security token:
At the top of any Salesforce page, click the down arrow next to your name. From the menu under your name, select Setup or My Settings—whichever one appears.
From the left pane, select one of the following:
If you clicked Setup, select My Personal Information | Reset My Security Token.
If you clicked My Settings, select Personal | Reset My Security Token.
Click the Reset Security Token button. The new security token is sent via email to the email address on your Salesforce user record.
If you ip is whitelisted / trusted and you still get invalid login not using the token, You MUST include the security_token='' in the connection string for it to work.
sf = Salesforce(username='USERNAME', password='PASSWORD', security_token='')
A security token is required to login.
Whenever your password is reset, your security token is also reset.
If you do not have a token and cannot reset it.
Try changing your password.
Thanks.
I was able to test that this was working with my security token against a developer org with no issues. This was all done as a standard user with no administrator privileges. Using the OrgId just failed out.
By resetting my password I received a new security token.
username = login for your instance.
password = your password
The code below should get you logged in.
from simple_salesforce import Salesforce
sf = Salesforce(username='username',password='password', security_token='whatever came in reset password')

How can I get oauth_access_token for facebook-sdk

I want to code that post facebook. So I decided to use python-sdk (https://github.com/pythonforfacebook/facebook-sdk).
Then I hit a problem.
graph = facebook.GraphAPI(oauth_access_token)
How can I get this "oauth_access_token"?
You need to use an authorization flow. Access tokens are the keys used after getting proper authorization.
An access token is an opaque string that identifies a user, app, or
page and can be used by the app to make graph API calls. Access tokens
are obtained via a number of methods, each of which are covered later
in this document. The token includes information about when the token
will expire and which app generated the token. Because of privacy
checks, the majority of API calls on Facebook need to include an
access token.
There are various ways to obtain an access token all explained in https://developers.facebook.com/docs/facebook-login/access-tokens/
For testing, one must create an app at https://developers.facebook.com/apps and can be issued an access token at https://developers.facebook.com/tools/access_token
Here is a way to get the user access token :
instance = UserSocialAuth.objects.get(user=request.user, provider='facebook')
token = instance.tokens
graph = facebook.GraphAPI(token['access_token'])
Maybe you've already figured this out, just in case somebody else is looking for it

Flask-login token loader

I'm setting up a Flask app with the flask-login extension. The flask-login documentation recommends setting up an alternative token generator that does not simply use the user ID and app secret to create the session token (which is the default method). But it doesn't provide any clear recommendations for how to do this.
So, for User.get_auth_token(), I'm using the make_secure_token function with the user email and password as parameters (so I get a hash of these parameters + app secret).
Next, I need to be able to get the user from the token with the token_loader callback. The default method for generating tokens in flask-login is to include both the raw user ID and a hash of the user ID + app secret. That makes finding the user from the token pretty simple - just grab the ID and look up the user.
But should I be exposing the user ID in the session token at all? If I don't, should I store the session token in the database or somewhere else with the user ID to make a lookup possible?
In short: does anyone know what the best practice is for creating a secure token & corresponding token_loader callback?
On the Flask mailing list, Matt Wright pointed me to his implementation in the flask-security extension. He uses itsdangerous to create a signed token which encodes a serialized (via URLSafeTimedSerializer()) list consisting of the user ID and the password hash. The token can then be decoded to grab the user ID.

Categories

Resources