how to get a more permanent access token - salesforce

The document at http://www.salesforce.com/us/developer/docs/api_rest/index_Left.htm#CSHID=quickstart_code.htm|StartTopic=Content%2Fquickstart_code.htm|SkinName=webhelp says
Salesforce uses authentication to allow users to securely access data without having to reveal username and password credentials.
but as far as I can tell, the only command that I can run to get an access_token is using my colleague's username and password like so
curl -d "username=yyyyyyy" -d "password=xxxxxxx" -d "client_id=zzzzzz" -d "client_secret=dddddddddd" -v -d "grant_type=password" https://login.salesforce.com/services/oauth2/token
and I have to regenerate that as the access_token keeps expiring. If it didn't, my colleague could just generate the token once and hand it off to me and be done with it.
How can I do this so he never has to give me his username/password AND my app will keep on working and working until he deletes the application from salesforce (which would hopefully invalidate the client_id and client_secret).
(That is how most APIs work at least so users don't have to give developers their username and password nor do we need to store username and password on production machines.) So how do we get this to work? OR are the docs completely wrong and I do need the user's login/password to access data even though that one line says otherwise.

Okay, this was rather annoying. In OAuth2, the proper way for an app that wants access to all data regardless of user and whether that user is logged in is grant_type=client_credentials which does not exist on Salesforce.
The work around is as follows
In the GUI, edit your app and in the "API (Enable OAuth settings)", add "Access and manage your data(api) or Full Access AND Perform requests at any time on your behalf (Refresh token)"
In the GUI, set the callback url to https://localhost/oauth (this is a hack and we will use this to our advantage later)
Now, go to the url (fill in the params with your data) https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=YOURCLIENTID&redirect_uri=https%3A%2F%2Flocalhost%2Foauth
Your browser will redirect you to https://localhost/oauth?code=YOURCODE NOTE: This code can only be used ONCE before you need to repeat step 3 and run again.
Run a POST request using the code in step 4 (the YOURCODE) to url https://login.salesforce.com/services/oauth2/token with the data in the body of grant_type=authorization_code&code=YOURCODE&client_id=YOURCLIENTID&client_secret=YOURSECRET&redirect_uri=https%3A%2F%2Flocalhost%2Foauth
NOTE: There are some %3Ds in the YOURCODE....you do not need to modify them and convert them to = and you can just leave them as is.
This now results in returning a refresh token you can use and the current access token you can use.
Now, just save the refresh token to your database (I am hoping it pretty much lasts until someone deletes the application and time will tell I guess).

You can use a regular interactive OAuth login flow to get a refresh token which can be used to get new access tokens as needed. see https://wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com for details.

Related

How to communicate securely to an Database with electron?

I am creating an electron application that connects to an Database and do POST and GET requests to retrieve and insert data into it, the problem is that in the code i have defined my database uri ( im using mongodb)
const uri = "mongodb+srv://<myusesrname>:<mypassword>#cluster0.wqbiu.mongodb.net/query?retryWrites=true&w=majority"
like in the example above, but if i pack my electron app the connection to the database as well as the credentials its visible if someone unpacks the app.asar file and look in the server.js file how i can solve this problem? i dont want any security breaches neither for me or the people that will be using my application, thanks in advance for any answer :)
An application that requires a secure connection to something cannot afford to have any username's or password's hardcoded into its code.
Instead, a procedure of authentication and authorisation is utilised.
Authentication is used to verify the user. IE: They are who they say they are, often achieved via the use of some type of login form.
Authorisation is used to verify the logged-in user is allowed to access the requested resource. EG: Is this user allowed to retrieve a list of all users email addresses from the database.
As a rough guide, a user will login with their username and password. You could use OpenID as well here if you wanted. Once the user is 'logged-in' you could set a cookie or session and save the session id in the DB against the user. Of course, all of this is done over HTTPS.
There are various ways to control the validity of the session such as but not limited to refreshing the expiration date / time every time the user hits the server, auto timeout if the user has not interacted with the server for more than X minutes, etc.
In your app, the user could try and interact with the database at any time, but if the user is not logged in, the server could return the appropriate response and prompt the user to login. Some form of API here is really the way to go.
If the user is logged in then then next step is to authorise the users request, ensuring they are allowed to perform what they are asking before sending a response back. If they are not authorised to access the resource (EG: Edit another user’s post) then an appropriate response is returned indicating so.
As you can see, securing your app will take some work but the result of not doing so could be devastating to you and your users.

Salesforce Server-to-Server integration without any user involved

I am working on a integration with Salesforce using REST APIs and, as part of the project, I need to send updates to Salesforce and these updates are not user triggered, they are system triggered.
Because of that, what I expect to see on Salesforce Field History is not a user name but the name of our Connected App (the app that made the update).
What I see today is the user name because the way the integration was made initially using OAuth Authorization Code flow.
To change that part of the project, I followed the link (OAuth 2.0 JWT Bearer Flow for Server-to-Server Integration): https://help.salesforce.com/articleView?id=sf.remoteaccess_oauth_flows.htm&type=5
Making that, I was expeting to generate a token for a System, not for a User, but that's not what happened: when I used the token generate from the JWT Bearer Flow and ran the update, the Field History still shows the user name.
What could I do then?
Which are the options in Salesforce to achieve the behavior I'm expecting?
The most important, in my opinion, is to have a Token for our system, not for a user.
Thanks!
Everybody is an user in Salesforce. Even if you access unauthenticated pages (some contact us form? case or lead capture) - it gets tracked under special Guest User.
It sounds stupid but gives you unified interface to control permissions (Profiles/Permission sets). You want guests to access only FAQ articles and make cases? Sure thing, do it in profile, don't get paranoid about people trying to guess right URLs. You think an app was hacked? You can terminate the session just like any other "user". Want to allow login only in certain hours and from certain IP? Sure.
An app connecting with JWT will still need username (main difference being it's "just" certificate for signing the request instead of password).
Your best bet is to create dedicated "Mr System", "SystemX integration" account. It sounds like waste of license but in the long run saves you questions "why did you edit my account at 1 am" and you could even use it as backup account if you use SSO and it ever fails...

Can the client modify react component state?

I'm building an admin page for an application and have a state value 'authenticated' that flips from 'false' to 'true' after a successful login (which is authenticated on the server) which then shows the actual admin panel.
Are component state values safe from tampering by the client? Basically, if the client can modify my 'authenticated' state value to 'true', they can skip the login and go straight to the admin panel (which I obviously don't want).
I read that React Dev Tools allows the client to modify values yet everyone says "validate on the server" but I am validating on the server and updating my state accordingly, if the user is approved. If it is not wise to have a state value manage this, what is the right way to conditionally show the admin page after a successful, server-side authenticated login?
I think this is an important question since tampering with state values in a React app can have huge negative consequences on data integrity within an app/database.
TL;DR: Either require an authentication token with every request or require authentication through a session.
Never trust users always. One potentially big issue is if you "hide" admin actions behind the admins page without requiring authentication.
For example, assume the backend server uses a REST API to accept commands. In the admin panel you get links to administrative actions like a button 'Delete Everything' that sends a DELETE request to server.net:8080/api/admin/everything without requiring any authentication. If you're a user, you can find that in the code potentially and then send a DELETE request to that address from anywhere without any repercussions.
We'd never give administrative privileges to anyone who would want to delete everything... Because we'll never untrust someone. Right?
Worse, someone might find the server and fuzz some inputs to it, and oops! They manage to delete everything (or even worse, GET everything stored in the database). This wouldn't be hard to do, especially if the server you use to authenticate is the same server you use to issue commands. History has proven "security through obscurity" to be a very bad paradigm. Every action should be authenticated, even if it seems like the actions will be hard to find.
Generally, providing a JSON web token or some other form of authentication token and having the user send that with every request is a good start at least, especially if it has an expiration date. The token would be provided through a separate request with valid credentials.
Sending a token with every single request obviously isn't ideal. There are a couple of other things to try. For servers using PHP, you can probably trust sessions (though very many people who know more than me would probably disagree). In more modern cases, you could try to use Web Sockets, requiring the token after connection. Then only after authentication with the token do you allow the user to make administrative requests.
That way, even if a user knows the exact command they can send to perform any action, the server won't let them without a current session or token. Unfortunately, unless you're already using Web Sockets or depending on a session, it will likely require a lot of changes. I'd consider this to be critical though.
It is always possible to tamper values in the front-end, there is no way you can rely solely on the front end to ensure security.
Your best approach is to implement some form of authentication and authorization on your backend. In this way, even is some users pretend to be admin, they will be blocked when you do the next request to the server.
Perhaps if you can send more information regarding your problem, we can think of a more specific solution.

Verify that a user can only query his own data/information

o/
I'm working on a smaller app, and its going pretty well so far. I talked with a friend about it and he suddenly made me realize something. How do i make sure a user is only able to query his own data from a Database in the cloud?
Its a very simple app, where you can create a user and make some personal shopping lists.
I thought about a couple of options, but I'm not sure what is the right direction to take - or even if any of them is the right one.
The username/id & password is stored locally and appended to the request, and checked against the DB every time.
A token is generated, saved both in the DB & stored locally as a "active" session, and every time a request is send, the token is appended to the request and checked.
...?
I'm sorry if i placed this topic have the wrong tags, since i was not 100% sure where they should be placed.
Well, from your description it seams that you are working on a "no backend" app. If it is the case I suggest you to take a look to Firebase since it will solve all your concerns about authentication and user authorization.
If your would like to use a more custom approach, simply consider that appending the username and a passowrd to a request is always not recommended and since you are using a token is also unnecessary.
Now, returning to the question, i will give you my vision related to contexts where an authentication token is used and thus a backend is needed:
when you log-in a user, you produce a token that is function of the user id
each user request must contain that token
the backend can extract the id of the user that submitted the request from the appended token
a policy or a specific condition will check that data that is going to be retrieved must belong to the user whose id has been extracted.
Hope this could help you

Securing Angular Application

I am creating an Angular application, and I am having trouble wrapping my head around the proper way to ensure my application and its users is secure.
I've been reading around many stack discussions, but I believe I am missing some core understanding of what is happening, please correct any errors you see written below.
So far I have a Sinatra server with many (currently mostly hypothetical) resource routes. A user can create an account using an email address and password that is stored in a database after being hashed with BCrypt. When a user logs in, the record is retrieved from the database by email and the password checked for authentication. It is from this point I am not sure how to proceed.
Prior to this I have simply set a session variable and had the server check that the variable exists in order to correctly route logged in users. Now my application is (currently) a single HTML page that uses Angular and ui-router to display different content, so most of the requests are simply returning JSON content.
It is my understanding that Restful applications should generally not use sessions, or rather that the server should respond identically to identical requests and not have its own data that shapes a response. But if I do not store something in a session variable, how could the server know that the client making the request has the correct permissions? And are sessions not stored in the browser anyway, thus not part of the server?
I believe from what I have read, it is possible to create a token which is essentially a large random string, return that string to the client and also store it in a database with a timestamp. The client then provides this token when making requests and the server hits the database to verify it exists and valid. But would the client not also have to store that string in a cookie? I suppose the angular application could store the token in a variable, which would persist while using the ui-router but not if the users navigates using the address bar.
I also do not understand how Basic Auth may or may not fit into this picture. Any help would be greatly appreciated, as well as a pointer to some good resources where I may find a better understanding of these concepts in general.
You want to read up on JWT. There are JWT libraries for Ruby and Angular.
I know you aren't using Node for your backend but a very easy way to see all the pieces working together is to run the angular-fullstack Yeoman generator. It uses JWT and the code is easy to follow.
As far as I can see, whatever you are doing with your sessions can work just fine.
This can be a sample JSON response from the server in case the user is not loged in :
{
"errorCode": 1,
"error": "User not logged in",
"data": {}
}
You can set your own error codes and handle what you want to do. You will send any data only if the user is logged in. For all the pages which don't require authentication, you can set data to whatever you want.
On the angularJS side, you can handle based on error codes, you can redirect the user to the login page and so forth.
The alternate way to support the same on multiple platforms is to use token based approach. The token based approach in simple words work this way.
The user logs in for the first time with his / her credentials.
The server verifies these information and creates a token from which the server is able to decode the user id.
Whenever the client makes the requests, it passes its token with every request.
As the server can decode the user information from the token, it sends or doesn't send the data based on whether that's a right token or not.
The token depends on a secret value. It can be same for all the users or differnet for each based on how you want to implement.
This is all done and you can look at
http://jwt.io/
As #andy-gaskell mentioned, you can look at
http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/
I'm very bad at explaining. Please let me know if any of this doesn't make sense.
you are missing the point of the REST concept. One of the main concepts in the REST apis is that the server should be stateless - this means that you should not store sessions or other "state" in your web server. Every HTTP request happens in complete isolation. Every request should include all data needed by the server to fulfill the request.
But if I do not store something in a session variable, how could the
server know that the client making the request has the correct
permissions?
You can store request scoped variables. This means that they should be only active during the same request. You can store the current logged in user in the request scoped variable. In that way you can get the current user in your invocation of the business method. I'm not familiar with Sinatra but here is the doc: http://www.sinatrarb.com/intro.html#Request/Instance%20Scope
But would the client not also have to store that string in a cookie?
of course you should store your access token in the client side
https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/
as #Andy Gaskell suggest take a look at JWT and fullstack application code generators and forget about the basic auth because it's really "basic".
more useful links:
If REST applications are supposed to be stateless, how do you manage sessions?
http://www.sitepoint.com/php-authorization-jwt-json-web-tokens/

Resources