Authenticating users in iPhone app - iphone

I'm developing an HTTP api for our web application. Initially, the primary consumer of the API will be an iPhone app we're developing, but I'm designing this with future uses in mind (such as mobile apps for other platforms). I'm trying to decide on the best way to authenticate users so they can access their accounts from the iPhone. I've got a design that I think works well, but I'm no security expert, so I figured it would be good to ask for feedback here.
The design of the user authentication has 3 primary goals:
Good user experience: We want to allow users to enter their credentials once, and remain logged in indefinitely, until they explicitly log out. I would have considered OAuth if not for the fact that the experience from an iPhone app is pretty awful, from what I've heard (i.e. it launches the login form in Safari, then tells the user to return to the app when authentication succeeds).
No need to store the user creds with the app: I always hate the idea of having the user's password stored in either plain text or symmetrically encrypted anywhere, so I don't want the app to have to store the password to pass it to the API for future API requests.
Security: We definitely don't need the intense security of a banking app, but I'd obviously like this to be secure.
Overall, the API is REST-inspired (i.e. treating URLs as resources, and using the HTTP methods and status codes semantically). Each request to the API must include two custom HTTP headers: an API Key (unique to each client app) and a unique device ID. The API requires all requests to be made using HTTPS, so that the headers and body are encrypted.
Current strategy:
My plan is to have an api_sessions table in my database. It has a unique constraint on the API key and unique device ID (so that a device may only be logged into a single user account through a given app) as well as a foreign key to the users table.
The API will have a login endpoint, which receives the username/password and, if they match an account, logs the user in, creating an api_sessions record for the given API key and device id. Future API requests will look up the api_session using the API key and device id, and, if a record is found, treat the request as being logged in under the user account referenced by the api_session record.
There will also be a logout API endpoint, which deletes the record from the api_sessions table.
Does anyone see any obvious security holes in this?

I agree with the oAuth comments - you can of course make oAuth work nicely on an iPhone - the UX is totally up to you. There are mechanisms (jQuery) to pull back the PIN from oAuth and use it (without the user re-typing the PIN into the app). That reduces the UX to
1) Display web page (in embedded control)
2) user enters user and password and presses button
3) oAuth response page is parsed automatically.
This twitter oAuth implmentation does that http://github.com/bengottlieb/Twitter-OAuth-iPhone using a pre-existing oAuth library.
However, back to your original question. That looks fine. The only item you don't mention, is that you need to provide a mechanism on the web app to allow the user to logout/deauthorize a device session (in case they have lost their device).

Related

Will the "Sub" claim in an Auth0 JWT always be unique?

I just have a quick Auth0 question. I've looked all over, but the more I look the more confused I get.
In the payload of the JWT that Auth0 gives me when I log in there is a Sub claim that look like this "sub": "facebook|123456789".
I'm just curious if sub will always be unique and if I can use it as a sort of foreign key in my database to link users to different tables.
The sub, short for subject, in this case is the User Id for the normalised user profile representing the user in Auth0.
Here, facebook|123456789 is the connection strategy (social connection of type facebook in your example) piped with the facebook ID for the user (which came from facebook). However, bear in mind, that with facebook, when you set up a Connection, you are actually setting up connection to a particular Facebook App - (the App ID and App Secret that you configure in Auth0 for that connection strategy). Long story short, for a single connection strategy of type facebook, defined under social connections in Auth0 Dashboard - then yes, this would be unique and could be a correlating identifier to a separate datastore with enriched info about that user profile etc.
Just bear in mind, if you were to create another separate App defined in Facebook, then setup a new Auth0 facebook connection to that facebook app, and login with same user - they would almost certainly receive a different sub since the facebook userId would be different. For example, it might be facebook|987654321 etc

OAuth - what to store on disk

TL;DR When using google oauth on desktop app, what to save on disk to avoid repeated sign in? Save the google user id? or the token? or an session id?
I'm creating an little desktop app, whitch must authenticate to my REST API server. I'm using google oauth2 for that.
The idea is, that when the desktop app will be authentivated, it generates some data that will be send to my server. The server will store the data with the google user id received from https://www.googleapis.com/userinfo/v2/me.
On the first run of the desktop app, it will open the default browser, with and url for my server and start an local http server. then:
my server will redirect the browser to google (with the clientid, secret, etc.)
user logs in and it will be redirected back to the server with the oauth code
server uses the code to get the token, and then the user profile and stores the token and the profile in db, then redirects the browser to localhost with an paramerer
the desktop app catches the parameter and stores it in an file on the disk
next time the desktop app will start it only reads the file for the parameter to send the generated data with it to my server
my question is: what the parameter should be? the google user id? the oauth token? an generated session id for this desktop app? or something else?
when it will be the google user id, it can conveniently sent the data with the user id and the rest server will just store it in db as is. but I don't think it's safe
when it will be the token, the rest server has to with every request also get the user profile from google with the token. and imho sending the token with every request isn't safe either
generating an session id means to store it with the user and the token on the server and the desktop app will just store it and send it with every request. but I don't know if it's safe to do that
As it's normally the case in software development you have a couple of options depending on requirements.
The mandatory requirement is that your client (desktop) application needs to send something to your REST API so that the API can perform up to two decisions:
Decide who the user is.
Decide if the user is authorized to perform the currently requested action.
The second step may not be applicable if all authenticated users have access to exactly the same set of actions so I'll cover both scenarios.
Also note that, for the first step, sending the Google user ID is not a valid option as that information can be obtained by other parties and does not ensure that the user did authenticate to use your application.
Option 1 - Authentication without fine-grained authorization
Either always sending the id_token or exchanging that token with your custom session identifier both meet the previous requirement, because the id_token contains an audience that clearly indicates the user authenticated to use your application and the session identifier is generated by your application so it can also ensure that. The requests to your API need to use HTTPS, otherwise it will be too easy for the token or session ID to be captured by an attacker.
If you go with the id_token alternative you need to take in consideration that the token will expire; for this, a few options again:
repeat the authentication process another time; if the user still has a session it will indeed be quicker, but you still have to open a browser, local server and repeat the whole steps.
request offline_access when doing the first authentication.
With the last option you should get a refresh token that would allow for your application to have a way to identify the user even after the first id_token expires. I say should, because Google seems to do things a bit different than the specification, for example, the way to obtain the refresh token is by providing access_type=offline instead of the offline_access from OpenID Connect.
Personally, I would go with the session identifier as you'll have more control over lifetime and it may also be simpler.
Option 2 - Authentication + fine-grained authorization
If you need a fine-grained authorization system for your REST API then the best approach would be to authenticate your users with Google, but then have an OAuth 2.0 compliant authorization server that would issue access tokens specific for your API.
For the authorization server implementation, you could either:
Implement it yourself or leverage open source components
⤷ may be time consuming, complex and mitigation of security risks would all fall on you
Use a third-party OAuth 2.0 as a servive authorization provider like Auth0
⤷ easy to get started, depending on amount of usage (the free plan on Auth0 goes up to 7000 users) it will cost you money instead of time
Disclosure: I work at Auth0.
There should be no problem sending the access_token with every request since they are created for that purpose and are thus short lived. You can use the Google Authorization Server endpoint to verify a token instead of using it to do a request for a users profile.
If you're only relying on Google for authentication, here's how your workflow can look:
the client (desktop application, in your case) retrieves the
Google id_token following the user's log in, and then sends it to
the server
the server validates the integrity of said token and extracts the user's profile data; this could mean a simple GET on Google's endpoint to verify this token: https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
On subsequent requests, nothing should change really, except that the user's login process will be automated (since he's given permissions & all), and thus much faster. #danielx is right, there's no problem with sending the token each and every time.

How to authenticate REST API with Stormpath Facebook integration

I am designing a simple REST API with Stormpath Facebook integration and wondering what would be the best pattern for user authentication. Currently I do not have any endpoint for user creation, so all requests to my endpoints are authenticated like this:
Get Stormpath Application object based on API_ID and API_SECRET configured in my app
Get Stormpath Account object based on Facebook token specified in every request
Based on account status authenticate request or reject
This follows more or less official guide and works fine because even though user account does not exist it will be created upon first get account request to Stormpath. Does it make sense and is it safe enough? I was looking for some documentation or best practices but could not find anything.
I would also need to get / generate unique user ID so I can make some relations with user data in my system - so another question, what is the best approach here:
Generate some unique ID, associate it with user email got from Stormpath and save in my system - I think this violates a little bit idea of such a service like Stormapth which encapsulates all user data
Do the same as above but store it in Stormpath Account customData
Use Stormapth user resource ID which can be obtained from user URI
Please advice.
Just for the record I am using Stormpath Java SDK and designing the API to be a backend for mobile social app so security is quite important for me.
Full disclosure, I manage Product # Stormpath. I'll be using your feedback to enhance the documentation.
It is hard to say if it is safe or not, without understanding the REST API you are building. If you made a REST API for cat pictures, my answer would be different compared to medical / financial information. One way to look at it, is that Facebook has the Graph API (REST) and they protect access requiring the same access token you are using. There are other flags that would cause me to say it isn't safe, like if you were using HTTP with no TLS.
To your second question, how to link Stormpath with your data. I wouldn't say you would violate anything about Stormpath by modeling out your application that makes sense to you and your app. Stormpath has customers that store EVERYTHING about their users in Stormpath. Stormpath also has customers that use Stormpath solely for authentication and authorization data and use customData to draw the link between a Stormpath user account and their data.
How / where you store the information is based on your needs. If you are starting with authenticating the user account with Stormpath, it would make sense to put the unique identifier / primary key in the user account's customData. If you are starting with querying your data store for the user data and need to get the Stormpath user account, then you will need to store the href for the user account in your data store.
A nice feature in the Stormpath SDK for Java is that when you do authenticate with Facebook, the returned object will disclose if the account was newly created or if Stormpath has existing account for the access token:
https://docs.stormpath.com/java/apidocs/com/stormpath/sdk/provider/ProviderAccountResult.html
This means that you will know when you need to create a record for the account in your data store and connect the two using customData and/or the user account href.

Spring boot REST token authorization and authentication best practices

What is the best practise for authorization and authentication of users in REST spring boot?
I am building web app with standard pages + REST API for mobile. I looked at many articles about Spring security and basically most of them goes with some sort of fitler approach that will allow or block REST calls. In my case, however, I have some auth logic based on who the user is. For example, there is a /update API that updates user information, and user can update himself, but cannot update other person.
Initially I thought to use next auth schema:
User calls auth API and pass name/password or cookie
System generates short life token, saves in it's database.
User get this token, updates his cookie (so JS in web application can read and use it)
When REST call is being make cookies are passed. At Controller, token is extracted, checked for expiration, query is done to database to validate token and get user id.
Based on user id, REST will be permited or blocked.
Is this the right approach to implement? I have a pretty big mess in my head after reading articles about spring boot security.
At least: session auth will not work for me (REST is stateless). I want to make auth for mobile device without storing login/password there.
Does it make sense to pass this token in the REST body itself? What in case of GET method?
Many thanks for sharing your knowledge.
Did you find a solution to your problem?
I have answered this problem elsewhere, if you are sure you won't want to open up the API to other developers/clients in the future (if you do then you should look at OAuth) then a simple token based solution will work.
Something basically along the lines of this:
Setup a standard html login page, that you can use for user login to the app
setup spring security to return a cookie on sucessful login with an authentication token
in your mobile app, embed a WebView (or equivalent) and load this login form - allow the user to login via that webview, on response grab the cookie and store the token (as mobile is generally single user, you can keep that pretty long to save mobile users having to keep logging in)
Add a security filter to the the REST API to authenticate against the token (from the mobile app pass the token in the header for example) - then you will be able to use normal spring authentication context for current users etc.
This approach is suggested by Google here: (EDIT: Google seems to have changed the page I originally read to be about using Google+ sign in and OAuth2.0 - I can't see a link to their general Mobile/API docs so here it is in the web archive :) )
I have also written up my implementation here:
Overview of the approach using Spring security
The code & details
Although this was really just an experiment/Proof of concept, it might be useful in your thinking.
Cookie approach seems perfect for the use case. Token can be tied up with user id. Filter can extract cookie and pass user id for example as header to apis - that should take care of GET...

Possible approach to secure a Rest API endpoints using Facebook OAuth

I've been reading a lot about the topic but all I find are obsolete or partial answers, which don't really help me that much and actually just confused me more.
I'm writing a Rest API (Node+Express+MongoDB) that is accessed by a web app (hosted on the same domain than the API) and an Android app.
I want the API to be accessed only by my applications and only by authorized users.
I also want the users to be able to signup and login only using their Facebook account, and I need to be able to access some basic info like name, profile pic and email.
A possible scenario that I have in mind is:
The user logs-in on the web app using Facebook, the app is granted
permission to access the user Facebook information and receives an
access token.
The web app asks the API to confirm that this user
is actually registered on our system, sending the email and the
token received by Facebook.
The API verifies that the user
exists, it stores into the DB (or Redis) the username, the token and
a timestamp and then goes back to the client app.
Each time the
client app hits one of the API endpoint, it will have to provide the
username and the token, other than other info.
The API each time
verifies that the provided pair username/token matches the most
recent pair username/token stored into the DB (using the timestamp
to order), and that no more than 1 hour has passed since we stored
these info (again using the timestamp). If that's the case, the API
will process the request, otherwise will issue a 401 Unauthorized
response.
Does this make sense?
Does this approach have any macroscopic security hole that I'm missing?
One problem I see using MongoDB to store these info is that the collection will quickly become bloated with old tokens.
In this sense I think it would be best to use Redis with an expire policy of 1 hour so that old info will be automatically removed by Redis.
I think the better solution would be this:
Login via Facebook
Pass the Facebook AccessToken to the server (over SSL for the
android app, and for the web app just have it redirect to an API endpoint
after FB login)
Check the fb_access_token given, make sure its valid. Get user_id,email and cross-reference this with existing users to
see if its a new or old one.
Now, create a random, separate api_access_token that you give back to the webapp and android app. If you need Facebook for
anything other than login, store that fb_access_token and in your
DB associate it with the new api_access_token and your user_id.
For every call hereafter, send api_access_token to authenticate it. If you need the fb_access_token for getting more info, you can
do so by retrieving it from the DB.
In summary: Whenever you can, avoid passing the fb_access_token. If the api_access_token is compromised, you have more control to see who the attacker is, what they're doing etc than if they were to get ahold of the fb_access_token. You also have more control over settings an expiration date, extending fb_access_tokens, etc
Just make sure whenever you pass a access_token of any sort via HTTP, use SSL.
I know I'm late to the party, but I'd like to add a visual representation of this process as I'm dealing with this problem right now (specifically in dealing with the communication between the mobile app and the web api by securing it with a 3rd party provider like facebook).
For simplicity, I haven't included error checks, this is mostly just to outline a reasonable approach. Also for simplicity, I haven't included Tommy's suggestion to only pass your own custom api token once the authorization flow is over, although I agree that this is probably a good approach.
Please feel free to criticize this approach though, and I'll update as necessary.
Also, in this scenario, "My App" refers to a mobile application.