allow secure form data to posted to my rails api - ruby-on-rails

I am creating a rails app which will help out businesses. These businesses have thousands of employees who will need a user account on this app.
I would like the business to be able to implement a form on their local intranet which can be submitted by users when they want to sign up to my app. This form posts some semi-sensitive fields to my rails API about their currently logged in user, such as their name and email address which would be populated by their server side code.
I can use this information to aid in the process of signing the user up to my site, and in identifying which business they actually do belong to. However, the form information along with an API key will need encrypting to avoid any data being stolen or a business being spoofed.
What methods of encryption are there out there that can be implemented on a variety of different languages and frameworks, and that involve the least amount of fuss to implement for the business?
OPEN SSL with Public and Private key encryption does seem like a good choice, but this does require some exchanging and creating of keys and can get complicated. Are there easier options?

Why not just have them post to your site over TLS/SSL? They can include their API key. SSL is about as cross-platform and cross-language as you can get. Any decent server-side language can make an HTTP request, so if you want them to send the request from their backend instead of directly from the form, that is easy enough.

You should use SSL to secure the transport layer as well as built-in Rails form protection (assuming you might do your own forms). Assuming this is intranet, you can generate an SSL certificate and run your Rails app through https://
Edit1:
You can also roll out a full API with OAuth/OpenID to authenticate users and authorize other applications. It all depends on if you own the data, users and ecosystem overall.

Related

OAuth2: Client Credentials flow

Problem: I am currently working on making a REST Api available to clients (the client in this case is not the normal end user who orders the articles, but the client's Web Api that communicates with my system). In order to order different products in my system, each customer may have several accounts for each country separately. Authentication is done by authenticating the client's WebApi application to my system (machine to machine). So it looks like this should be done using OAuth2 Client Credentials Flow based on the article https://learn.microsoft.com/en-us/azure/active-directory/develop/authentication-flows-app-scenarios#scenarios- and-supported-authentication-flows, but I have doubts about the issue of client accounts for each country separately.
Question: This should be solved by creating a ClientId and ClientSecret for each client account per country separately or, however, one client account should be created, while the country should be sent by the client in each request to the Api or before adding the country as a scope or claim to access token.
Additionally, I am not sure if Client Credentials Flow is a good choice in this situation, so I would be very grateful for any suggestions.
CLIENTS
Ideally each client company should have a single client credential for getting access tokens. In sone cases, such as when there are different legal subdivisions, this can be extended. By default use a single value, but you need to understand your clients.
A client credentials flow between companies can involve stronger credentials if needed, such as JWT client assertions or Mutual TLS - as in this advanced tutorial.
CLAIMS
In your system you should map domain specific data needed for authorization against each client ID. This might include country specific access to products or whatever makes sense for your scenario.
This data can then be either included in access tokens at the time of issuance, or looked up when an access token is first received, then cached for subsequent requests with the same token. Step 3 of my Authorization Blog Post explains a couple of design patterns here.
API REQUESTS
How the client gets data in API requests is interesting:
Is data for all countries owned by the caller? If so let them select the data they want via a country parameter during API requests.
If the API client shoild never be able to see data for a country, that suggests that in at least some cases you need different clients per country.
SUMMARY
Define clients in terms of what makes sense for those companies. Avoid an explosion of clients in order to manage access rights for the same data owner. Exact solutions depend on your domain specific requirements. OAuth is a framework that is meant to be adapted.
If your entire existing data-model silos 'countries' by a concept of an account, then a set of credentials per account might be the easiest.
But it sounds to me that your data-model doesn't fully capture your actual business well. It sounds to me like you have a concept of a 'customer/client' that has access to one of more 'accounts', each representing a country.
So a more correct way to model this might be to structure your API so that a single API client can access all of the related accounts, and your API should perhaps be structured so that the idea of an accountId is somehow passed (usually in the URL for REST apis). For example, each API endpoint can be prefixed with /account/123.
To me this is more of a data-modelling and API architecture question than anything OAuth2-specific.

How to secure basic methods like user creation in an API

I'm learning about developing APIs with rails, but I can't find how to secure the base methods like user creation. Let's say I have a rails backend API and a frontend mobile app. I want the app to be able to make API calls to create a new user. Off course, not everyone should be able to create a new user, so it should have some kind of authentication. I could use basic or digest authentication (doesn't really matter, because I'll definitely use SSL), but then I would have to hardcode the credentials into my app. If the credentials are discovered somehow, I would have to change them, but that would mean that all instances of the app are no longer authenticated and they can't create users anymore.
The things I would like to have:
Only my apps should be able to use the user creation calls.
It should be easy to change the credentials, or the credentials should change automatically over time. If they would involve the date and time for example, it would be harder to crack.
It should be impossible (or VERY hard) to beat the system behind it, while having knowledge of a couple of the credentials over time.
Would it be possible for example to let my apps generate public and private key pairs at random and use them? What's the standard way of securing these calls?
Thanks in advance,
Rugen Heidbuchel
I could share my own experience:
https protocol communication with API. That is your last sentence about private/public keys, all is built in into https.
Doorkeeper (we combine it with Devise) gem for Oauth (github accounts in my case) as authentication, while you can use pairs of user/passwords instead.
CanCanCan gem as authorization (User creation restriction is about authorization and not authentication)
Set of that three tools should provide essential security level for your API. I believe cancancan could be under discussion, while devise is mostly industry standard.

Client-server user authentication

UPDATE: I failed to mention earlier that we want solution that will be flexible with authenticating users from within our databases or by asking other servers to tell us if the user is authenticated. It is also worth mentioning that these other servers are not under our control so we can't enforce a specific user model.
I had a long and hard read on OAuth and OpenID but they are both not a suitable solution for our situation and will make the process harder to the user. This is something that has been solved a thousand times, yet I cannot find the solution.
What we are looking for is a framework that can be used in a REST services server to authenticate users (no third-party clients involved) with their username and password.
The solution must not pass the username and password except the first time on login and use tokens for further authentication. Even though OAuth does use tokens, it is designed to allow third-party clients access to the service-providers resources. That is not the case here, the services are for our own application only, the only thing needed is user authentication.
What do you guys think is the most appropriate solution?
Configuration:
-Spring server that provides RESTful services with our thinking going towards using Spring Security with some user management and token management framework.
-iOS Device that will be making HTTPS calls to the server.
What we ultimately want is to have the device send a login request and receive a token if the login was successful, later on make requests using that token. Just like Facebook, excluding third-party involvement.
Is there something that is ready to be configured in our server? Or should we consider building our own token management, comparison and generation software?
Is using Spring-Security with an iOS application without involving storing cookies or redirecting to pages possible?
OpenStack offers as part of it's many projects related to open source cloud... the project Keystone. Which does this pretty much exactly what you want.
You might want to check it out here:
http://docs.openstack.org/developer/keystone/

Implement user authentication against remote DB with a Web Service

I'm just starting reasearch about the best way to implement user authentication within my soon-to-be app.
This is what I have so far:
A desktop (Windows) application on a remote server. That application is accessed locally with a browser (it has a web console and MS SQL Server to store everything).
The application is used with local credendials stored in the DB.
This is what I'd like to accompllish:
Provide access to some information on that SQL Server DB from my app. That access of course must be granted once a user has id himself with valid credentials.
This is what I know so far:
How to create my PHP web service and query info from a DB using JSON.
How to work with AFNetworking libraries to retrieve information.
How to display that info on the app.
What I don't know is which could be the best method to implement user authentication from iOS. Should I send username and password? Should I send some hash? Is there a way to secure the handshake?
I'd for sure appreciate any advise, tip, or recommendation you have from previous experience.
I don't want to just implement it but instead I want to do it as good as possible.
There have been books written on this, so any answer given here is necessary incomplete. So, I'll give you an outline of the simplest thing that actually works. The bare minimum for securing a service like this is to use HTTP Basic Authentication (supported natively by both AFNetworking and PHP) secured by SSL/TLS.
Basic Authentication is a way of hashing (not encrypting) credentials in a standard way and sending them as one of the headers in your request (Authorization: Basic <Base64-encoded concatenated credentials>). AFNetworking supports this as part of its AFHTTPClient class (see the -setAuthorizationHeaderWithUsername:password: method). PHP parses the authentication header into a pair of server variables ($_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']). From here, you just check the username/password combination against your user database and allow or forbid access to the resource.
The reason it's crucial to pair this technique with HTTPS is that the credential hash is easily reversible; you're basically sending the password in the clear, so it can be grabbed by anyone listening to your traffic. Setting up a certificate and sending your requests over the secure channel prevents this type of vulnerability.
If you want to be a little more sophisticated, two-legged OAuth is also a viable choice for this scenario.

Looking for suggestions for building a secure REST API within Ruby on Rails

I'm getting started on building a REST API for a project I'm working on, and it led me to do a little research as to the best way to build an API using RoR. I find out pretty quickly that by default, models are open to the world and can be called via URL by simply putting a ".xml" at the end of the URL and passing appropriate parameters.
So then the next question came. How do I secure my app to prevent unauthorized changes? In doing some research I found a couple articles talking about attr_accessible and attr_protected and how they can be used. The particular URL I found talking about these was posted back in May of '07 (here).
As with all things ruby, I'm sure that things have evolved since then. So my question is, is this still the best way to secure a REST API within RoR?
If not what do you suggest in either a "new project" or an "existing project"scenario?
There are several schemes for authenticating API requests, and they're different than normal authentication provided by plugins like restful_authentication or acts_as_authenticated. Most importantly, clients will not be maintaining sessions, so there's no concept of a login.
HTTP Authentication
You can use basic HTTP authentication. For this, API clients will use a regular username and password and just put it in the URL like so:
http://myusername:mypass#www.someapp.com/
I believe that restful_authentication supports this out of the box, so you can ignore whether or not someone is using your app via the API or via a browser.
One downside here is that you're asking users to put their username and password in the clear in every request. By doing it over SSL, you can make this safe.
I don't think I've ever actually seen an API that uses this, though. It seems like a decently good idea to me, especially since it's supported out of the box by the current authentication schemes, so I don't know what the problem is.
API Key
Another easy way to enable API authentication is to use API keys. It's essentially a username for a remote service. When someone signs up to use your API, you give them an API key. This needs to be passed with each request.
One downside here is that if anyone gets someone else's API key, they can make requests as that user. I think that by making all your API requests use HTTPS (SSL), you can offset this risk somewhat.
Another downside is that users use the same authentication credentials (the API key) everywhere they go. If they want to revoke access to an API client their only option is to change their API key, which will disable all other clients as well. This can be mitigated by allowing users to generate multiple API keys.
API Key + Secret Key signing
Deprecated(sort of) - see OAuth below
Significantly more complex is signing the request with a secret key. This is what Amazon Web Services (S3, EC2, and such do). Essentially, you give the user 2 keys: their API key (ie. username) and their secret key (ie. password). The API key is transmitted with each request, but the secret key is not. Instead, it is used to sign each request, usually by adding another parameter.
IIRC, Amazon accomplishes this by taking all the parameters to the request, and ordering them by parameter name. Then, this string is hashed, using the user's secret key as the hash key. This new value is appended as a new parameter to the request prior to being sent. On Amazon's side, they do the same thing. They take all parameters (except the signature), order them, and hash using the secret key. If this matches the signature, they know the request is legitimate.
The downside here is complexity. Getting this scheme to work correctly is a pain, both for the API developer and the clients. Expect lots of support calls and angry emails from client developers who can't get things to work.
OAuth
To combat some of the complexity issues with key + secret signing, a standard has emerged called OAuth. At the core OAuth is a flavor of key + secret signing, but much of it is standardized and has been included into libraries for many languages.
In general, it's much easier on both the API producer and consumer to use OAuth rather than creating your own key/signature system.
OAuth also inherently segments access, providing different access credentials for each API consumer. This allows users to selectively revoke access without affecting their other consuming applications.
Specifically for Ruby, there is an OAuth gem that provides support out of the box for both producers and consumers of OAuth. I have used this gem to build an API and also to consume OAuth APIs and was very impressed. If you think your application needs OAuth (as opposed to the simpler API key scheme), then I can easily recommend using the OAuth gem.
How do I secure my app to prevent
unauthorized changes?
attr_accessible and attr_protected are both useful for controlling the ability to perform mass-assignments on an ActiveRecord model. You definitely want to use attr_protected to prevent form injection attacks; see Use attr_protected or we will hack you.
Also, in order to prevent anyone from being able to access the controllers in your Rails app, you're almost certainly going to need some kind of user authentication system and put a before_filter in your controllers to ensure that you have an authorized user making the request before you allow the requested controller action to execute.
See the Ruby on Rails Security Guide (part of the Rails Documentation Project) for tons more helpful info.
I'm facing similar questions as you at the moment because i'm also building out a REST api for a rails application.
I suggest making sure that only attributes that can be user edited are marked with attr_accessible. This will set up a white list of attributes that can be assigned using update_attributes.
What I do is something like this:
class Model < ActiveRecord::Base
attr_accessible nil
end
All my models inherit from that, so that they are forced to define attr_accessible for any fields they want to make mass assignable. Personally, I wish there was a way to enable this behaviour by default (there might be, and I don't know about it).
Just so you know someone can mass assign a property not only using the REST api but also using a regular form post.
Another approach that saves building a lot of the stuff yourself is to use something like http://www.3scale.net/ which handles keys, tokens, quotas etc. for individual developers. It also does analytics and creates a developer portal.
There's a ruby/rails plugin ruby API plugin which will apply to policies to traffic as it arrives - you can use it in conjunction with the oAuth gem. You can also us it by dropping varnish in front of the app and using the varnish lib mod: Varnish API Module.

Resources