Flex App Embedded in Rails App w/Authentication - ruby-on-rails

We have a Rails 3 app using session-based authentication (modified acts_as_authenticated), and a Flex app that needs to be embedded in an html.erb template. The Flex app needs to access routes that have a before_filter set to check if the user is logged in. When interacting with the HTML site, this causes the user to be redirected to a login page, then sets a Rails session property (tied to a cookie) to record that the user is logged in when making future requests.
The Flex app needs to access XML that's generated by Rails (behind the before_filter) and I don't want to force the user to log in twice -- what should I be passing as a flash parameter to the Flex app so that it can present as "already logged in" if that session exists (ie, the user has logged in via the HTML interface)? I haven't dealt with this kind of problem before so I'm not sure if I'm even asking the right question. Any advice appreciated!

Integrating flash into your authenticated service can be tricky. You can't rely on normal http sessions or cookies to manage authentication for you. What is generally regarded best practice is to generate a unique token for each logged in user to pass on every request to the server to prove that they are in fact a logged in user. for example:
They log in through an html form.
When you serve up a swf that is going to access authenticated content you give it a flashvar of token=49r03f0239fhduffnkdjfgnas or something like that.
This token is generated server-side and stored somewhere to be checked on requests.
On every request to the server you pass this token and check it's validity.
If it's good you perform the action and return the data.
If it's bad you prompt the user.
notes:
tokens should be long and unguessable like a session variable.
each time they log in you need to generate a new token.
each time they log out you need to destroy the token.

Related

Dropbox OAuth2 API always prompts user for permission when a refresh token is requested

I'm writing an offline application that uses the Dropbox API. When a user comes to the application, I'm using the https://api.dropbox.com/oauth2/token (docs) to get a refresh_token, which I store for later use.
I am calling the same endpoint every time the user logs in (unless I've already got the user's data in a cookie). I'm not sure that this is the best way to go about it: I at least need to get the user's account_id, so that I can look up their refresh_token in the database if I already have it. But every time I call https://api.dropbox.com/oauth2/token, the user is redirected to the Dropbox app authorization interface, as if they've never approved the app before.
So I would either like to know how to stop Dropbox from forcing the user to re-authorize an app every time. Or, if that is just how https://api.dropbox.com/oauth2/token is supposed to work, I'd instead like to be able to get their account_id somehow when they visit my page.
(In case it's relevant, the app is still in development mode at this point.)
The https://api.dropbox.com/oauth2/token endpoint is an OAuth endpoint that the app can call to get an access token/refresh token. Being an API endpoint, it does not itself redirect the user to the Dropbox app authorization page.
The Dropbox app authorization page is at https://www.dropbox.com/oauth2/authorize (documented here), and the app decides if/when to direct the user there to authorize the app.
You generally only need to send the user through the app authorization flow (sending them to https://www.dropbox.com/oauth2/authorize and then calling https://api.dropbox.com/oauth2/token) once per user for an "offline" application. Once you do so, you should store the resulting refresh token for that user. You'll typically store the refresh token for that user tied to their user account in your own app.
Exactly how you manage the user accounts in your own app will depend on how it's built, but, as it sounds like this is a web app, typically you would use the user's browser cookies to identify the user when they return to your page so that you can look them up in your database and retrieve their details, such as their corresponding refresh token. (Or, if they're not already signed in to your web app, you would have them do so first.)
Greg's answer is very helpful, and very politely addresses my misunderstanding of the auth flow. (I was revisiting old code I'd written years previously—obviously I should have documented it better than I had!)
In the end I believe that Dropbox was forcing me to reauthorize because my application was in development mode, and had a small user base. When I used the identical code in an app set to production mode, it stopped forcing me to reauthorize. So the “problem” is really a Dropbox security feature, and the solution was just to use production mode.

Rails app Query params and Cookie based login

I am trying to find a way to distribute a Ruby on Rails app selectively by sending them an email with the link that logs them in. This should be the only way to get to the page hosted at a unique subdomain. Additionally, we don't plan on having a login wall so the access would need to be guarded by using Cookies or the Query URL params.
A couple of questions regarding this:
Is it possible to leverage cookies exclusively to achieve this? I.e Any way to embed cookies within the URL sent in the email itself?
An approach I felt that might work is to embed the user ID (encrypted) in the URL in the email. In order for the users to not need to bookmark this URL or go back to the email to access this link, I was planning to store their session ID via a browser cookie. Any issues with this approach?
How to avoid wandering users(i.e users who haven't received this email) to access this page (i.e a nice way to raise a 404 error)?
Any other cleaner ways to accomplish this task?
Is it possible to leverage cookies exclusively to achieve this? I.e
Any way to embed cookies within the URL sent in the email itself?
No. You cannot "embed cookes in a URL". Cookies are set via the SET-COOKIE header in a response or through JavaScript.
An approach I felt that might work is to embed the user ID (encrypted)
in the URL in the email. In order for the users to not need to
bookmark this URL or go back to the email to access this link, I was
planning to store their session ID via a browser cookie. Any issues
with this approach?
Yes. You should generate a random token thats not tied the users id.
How to avoid wandering users(i.e users who haven't received this
email) to access this page (i.e a nice way to raise a 404 error)?
Create time limited access tokens that can only be used once by the user. There really is no other way for you to actually know that the person requesting the URL is the recipient of the email.
What you are describing can be accomplished with Devise Invitable which is a pretty good community tested point of reference if you want to reinvent the wheel.
When you invite a user Invitable creates invitation tokens which are stored in the users table. This is just a random string. There are also timestamp columns that expire invitations automatically.
The token is included in the URL in the invitation email as a query parameters.
When the user clicks the link the controller looks up the user based on the token and nulls users.invitation_token so that it cannot be used again. This stores the user id in the session and takes the user to a screen where they edit and finalize their account by setting a password.

Auth0: How to enable silent authentication in Hosted Login Page?

I'm using hosted screen of Auth0. I want the following scenario to work-
Let's say I have 2 apps- app1 and app2.
One of the users signed in by providing email+password in app1.
User then navigated to app2.
Auth0 detected that the user has already signed in, so it redirects the user back to app2 WITHOUT having her signed in again.
But what I'm facing is this screen-
How can I save my user this additional click? How do I implement silent authentication? I know that you have to pass prompt=none to /authorize api, but since I'm not manually calling the api, how do I make the lock call /authorize with prompt=none?
What you want is silent SSO which is related to SSO but kind of independent.
The key is in the prompt param. This needs to be none in order for the user to not be prompted for login when he's already logged in Auth0's Authorization Server ("central SSO").
One annoying thing I found is that prompt is taken literally, so if the user is not logged in yet, he will not be prompted to login (you'd think it'd make sense to prompt the user when not logged right?).
In this case SSO will redirect to your app's /authorize with an error like "authentication required" and you'll have to handle it by redirecting the user to your /login endpoint again but passing prompt=true so that it knows that this time he'll have to pass prompt=true to Auth0's hosted login page.
To make things a bit uglier, currently passport-auth0-openidconnect seems to ignore the params you pass to the strategy unless you monkey patch one of the methods involved (I created a PR for it, don't when will be approved and/or if makes sense).
Essentially:
Pass prompt=none
If user is already logged in, he will silently be logged in your app as well
If user not logged in, user will be redirected to your app with "login required" error
In that case you'll have to pass prompt=true
I know it's a bit fiddly but I hope this helps you :)
PS: Another thing to bear in mind - I now just found out that it works perfectly when using Github as connection but when using google-oauth2 it blows up complain about the prompt param :|

How do I add a token to my request in Rails 4?

I have an upload application that will be accessible by multiple other applications. I want user security from those applications to be federated to this upload hub. I'm doing it with HTTP tokens that are shared between the applications.
I have read 5 different articles on how to secure an API in Rails. I have everything set up properly in the upload hub app. I have keys set up in my User table, and I have shared this key with the user table in the other apps. I have the code in place to check for this key, and to locate the appropriate subscription. Upon failure, the user is redirected to the login page of the source application.
There's just one thing. I can't find anywhere how to create the actual request! I want the users in the other applications to click an "upload" link that will take them to this application. No problem creating the link, of course. The problem is, how do I add the token to the request?
See, I'm not making programmatic requests to an API... The user is actually going from one app to another. I want the upload hub app to check the request and say "Oh, there's this big long key. Let me see if I can find a user associated with that. I'm obviously not going to put it in a query string.
The only thing I've come up with on my own is to have a bit of jQuery code that constructs a form with a hidden item containing the key in it, which it would get from a hidden field on the current page, then do a POST against the upload hub app. That's not really a token, but it's doable. Surely there's a better way?
UPDATE
I went the jQuery "postGo" route where I construct a form with a hidden field and send it as a parameter to the other app. I had forgotten about protect_from_forgery though. However, even after turning protect_from_forgery off, Rails somehow still strips all parameters except for controller and action from outside requests. Undocumented feature? Or maybe I missed the documentation.
Really, I just want SSO on a couple of apps. It looks like I'm going to have to create an Oath provider. Sure are a lot of hoops to jump through to federate a simple session on some apps that I own.
Here's a possible way of doing this.
In the upload controller method of the app, instead of redirecting the user directly, make a request to the upload hub app.
In the upload hub app, add a controller method and generate a token, store it and a user's credential in redis, or other storage of your choice, then response the app with the token.
Your app's upload controller method receive the response from upload hub, then give 302 response back to the client, with the token included in the redirect url.
The client redirects to the upload hub
The upload hub router accepts this format, the token can be in a query string.
Check in redis and find it by the token and match the user's credential

Rails inception - how to handle a login session within a login session

I must build a Rails API, which responds to requests from an iPad app. I have, among other things, a Shop model, a User model and a Product model.
The iPad app works like that - once started, first the shop must log in with an ID and a password. This is done by the shop manager (probably in the morning, at the beginning of the working day or even just once, if they never log out). This happens on multiple iPads. Then, an iPad is given to a customer, who, within the “session” of the shop, logs in as a user. The point of this is, that a user can log in with the same credentials in different shops and depending on this, they can see different products in the iPad app.
So, within a Rails session I need to keep a current_user, but also a current_shop. The question is - how do I implement this?
I was thinking of the following - after the shop manager enters id and password, the API returns some token, which is persisted on the iPad. Then - when the user logs in, this token is sent along with their credentials, so that, at the moment of login I know in which shop the user is and know which products to return in the initial response after login. I also save the shop token in the user’s session.
I would first like to know if my general idea is correct. Also, I would like to know how would you implement it. I was thinking of using Devise for the user and hand-rolled authentication for the shop, but I must figure out how to integrate both.
Devise does allow you to use any model and multiple models in parallel. This allows you to use all the nifty helpers like current_user and authenticate_shop!.
What devise doesn't bring out of the box is an API authentication mechanism. That you can (and have to) implement yourself
Using tokens for each of the shop and user accounts seems straight forward. You can even use the same basic mechanism (maybe via HTTP-Header).
before_filter :authenticate_xxx_via_token
def authenticate_xxx_via_token
xxx_id = params[:xxx_id] || request.headers["X-XXX-ID"]
xxx_token = params[:auth_token] || request.headers["X-XXX-AUTH-TOKEN"]
xxx = xxx_id && Xxx.where(id:xxx_id).first
if xxx && Devise.secure_compare(xxx.authentication_token, xxx_token)
sign_in xxx, store: false
end
end
So do this once for each model and you can then protect your controllers/actions via authenticate_xxx! and use current_xxx.
Finally, don't forget to add SSL to your service or all of this is of little use.
I guess, you're integrating an API driven application, using devise will be of limited use to you. You could do it but I have a feeling it will cause more pain than it is worth.
Use Rails built'in has_secure_password - http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html
The simplest possible flow without session tokens would go like this:
store manager's username and password into the iPad app (you can send an api call to the host to verify it's OK) and the app stores those values in its process memory (not on the disk!)
in subsequent API calls you resend the manager's username and password alongside with the customer's username and password and you verify both in before_action of your base controller
A bit more secure solution would be to use a session token which supports multiple ipads:
store manager enters his username and password into the ipad app and ipad app sends a store authentication call, you verify the credentials and return a SecureRandom.base64 digest and you set Rails.cache shop_owner/#{digest} key to value of shop_id for later retrieval, on the app you are free to put the digest on the disk
in every subsequent request the digest is sent alongside the customer credentials, in the before_action you check the cache for shop_owner/#{digest} and retrieve the store ID from there

Resources