Consume API with basic authentication using Javascript without exposing key pair - javascript

I have a private API, where I'm using basic authentication as my security layer. Right now the API is consumed by my iOS app, so no one is able to see the key pair.
I'm creating the same app for the web now, using React and Javascript and need to consume the same API using basic authentication.
How can I use my API key pair in Javascript without exposing that key pair to the public? Is such a thing even possible?

As #Andrew mentioned, that is not possible, you can just make it harder to get, but it'll be there somewhere on the client code, and that's enough to say you're exposing it.
If you're open to alternatives, I suggest you to use a per user authentication for the first request, and then a token based authentication for further requests. That token can be a JSON Web Token and it's the flow I'm talking about:
This is the way it works, taken from JWT's official documentation:
In authentication, when the user successfully logs in using their
credentials, a JSON Web Token will be returned and must be saved
locally (typically in local storage, but cookies can be also used),
instead of the traditional approach of creating a session in the
server and returning a cookie.
Whenever the user wants to access a protected route or resource, the
user agent should send the JWT, typically in the Authorization header
using the Bearer schema. The content of the header should look like
the following:
Authorization: Bearer <token>

TL;DR: No.
If the client needs to be able to connect to the API directly, there is no surefire way to prevent them from discovering the API key, as they must, by design, be able to access it in order to send it in the request. You can take measures to obfuscate it, by storing it encoded (but the client will have to have the decoding algorithm as well).
This is in fact also true with your iOS app. Someone can reverse engineer the binary or intercept the requests and view the header, discovering the API key.
A possible “solution” is likely to have each client get their own API key, be it temporary or permanent, that is in someway locked to their account/device/session to limit reuse.

Related

What Uniquely Identifies a Client Making a Request to Web API?

Let's say I write a piece of code that makes an http call to a web api, something like:
$http.get('www.myapi.com/api/controller/endpoint').then(function(resp){...})
I then give this code to two people that live in different cities and they hit my API from their respective houses (just from some browser). What information can my API get out of the http request that will allow me to tell apart person A and person B calling it? Is the IP always available? Is the MAC address ever available? What else is there?
How can person A pretend to be person B when calling my API?
Furthermore, what if person C calls my Web API from their own Web API (backend)? Will the same information be available, or what will be different?
This is a general question, but if you want to get specific, let's assume ASP.NET Web API 2 is receiving the http requests.
You're describing a desire for pre-authentication.
The IP will always be available. You could restrict the service to only those IP ranges. It's not a good way to do authentication.
Trying to get around having to perform authentication is not safe. You should use a proper authentication method. Combining IP restrictions with other methods is fine.
John Meyer's answer is essentially pre-shared token based user authentication. Having a valid token constitutes being constantly logged in. The token can be compromised far more easily than a typical token based user authentication that establishes a temporary token with a limited lifetime.
If you decide to go the pre-shared token route, please use a method that supports proper rotation or permutation of the token over time, such that it isn't vulnerable to replay attacks.
Your best option for this scenario is typical session-token based user authentication.
If you're actually not interested in who is using your service, only that they be uniquely identified, you can safely establish a session (or permanent, or arbitrary lifetime) cookie per user by the http Set-Cookie header that all clients should automatically respect and support, then use that as your method of tracking.
My team has accomplished this by requiring that an identification header be included on all requests. This does require some customization on the part of the calling party, but does not necessarily require that the user be logged in. Of course, the value of the header could be change by malicious users so if these calls need to be very secure you will need traditional authentication.
you seem really confused about this. what you are looking for is called authentication.
as you tagged C#, i am assuming you are developing your api in C#. I recommend checking Web Api.
there are a couple of authentication methods available these days. if you are developing a rest api, you can use json web tokens.
you can get a lot of information about the client calling your api via http headers.
I think you can always go with fully authenticated. I see your desire to go for a semi secured set of endpoints but I don't think any of the approach would serve you best. MAC, ip, user-agent, custom fields anything can be spoofed to be honest. Going with a bearer token or session token is your only bet here. For public apis you can limit user requests based on ip or you can try finding out whether a specific ip is trying to exploit you and thus block it but finding true identity might not be possible anyway.

Moving from Session-based token mechanism to OAuth 2.0 mechanism

I own a Play Framework application acting acting as a backend server providing a set of REST APIs.
At client side, I own an AngularJS application that calls APIs from backend-server through AJAX.
Currently, I make use of a solution based on Session-token mechanism.
Meaning that each time a user logs in successfully, a cookie is retrieved at client side containing an authentication token.
At each request then, the cookie value (the auth token) providing by the client request is extracted on the server and if valid, the request is made.
Now I want to use OAuth 2.0. Reasons are? :
It's a great standard way to secure API, avoiding the use of a datastore (Memcached) to keep auth tokens at server side, as I'm currently providing.
I want to provide a better secure than a sole cookie, by providing some client_secret and nonces to avoid some replay attacks etc...
I want to restrict the amount of clients capable to call even public REST API I provide, meaning API that allows anonymous call, like listing a list of items for instance.
The point is that I don't involve a third party, since all protected resources are on my own.
I came across this article explaining how to secure internal REST API with OAuth 2.0 implementing a 2-legged instead of a 3-legged as usual.
However, I can't figure out how the Client Credentials flow could authenticate a specific user, when calling for a REST API that needs to have a user authenticated.
Indeed, Client Credentials flow seems to be based on a global client_id, client_secret keys (global to the app, so in my case to my Javascript app), and therefore not enough specific to target a specific user and controller its specific rights.
Any help would be great.
Seems like you should use "Resource Owner Password Credentials Grant" (https://www.rfc-editor.org/rfc/rfc6749#section-4.3). It is dead simple - put client ID/secret in Authorization header and put user name/password in query variables. Here is an example from the RFC:
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w
Server side you can check for both validity of the client (your javascript app) as well as the user. Just remember that it is impossible to protect the client credentials as it will be embedded in your (downloadable) JavaScript code. The user name/password is entered directly by the end user.

How to Secure ASP.NET Web API with Cross Domain AJAX Calls?

I want to create an API at www.MyDomain.com that is accessible from public websites www.Customer1.com and www.Customer2.com. These public websites display each customers inventory and do not have any login features. They will use AJAX calls to read data from my API.
How can I secure the API so that it can be accessed via AJAX from different domains but no one can access the API to be able to scrape all of my customers data and all of their inventory?
I have tried thinking of different solutions on my own but they would all either require people to login to the public websites (which isn't an option) or it would require some secret "key" to be displayed publicly in the browser source code which could then be easily stolen.
Any ideas would be greatly appreciated.
Thanks!
P.S. Are their any obstacles that I am going to run into using Javascript & CORS that I need to look into now?
Anything that is accessible without authentication from a browser is by definition insecure, so you can't stop that. Your best bet is to have to have a relationship with the owner of customer1.com and customer2.com - the server apps for those two websites would make an HTTP call to you and authenticate with your service. Going this way also avoids the CORS issues you're talking about.
If you've already designed the client functionality, you can still probably do it without much change to the javascript - have it point to customer1.com for its AJAX call instead of your API, and customer1.com would accept this request and just act as a proxy to your API. Aside from the authentication, the rest of the request and response could just be pass-throughs to your API.
You can use Microsoft.AspNet.WebApi.Cors.
It's just need add ONE line at webapi config to use CORS in ASP.NET WEB API:
config.EnableCors("*","*","*");
View this for detail.
The simplest way to provide a minimum security here is to provide some kind of token system. Each app has its own token, or combination of tokens which it must pass to the server to be verified. How you generate this tokens is up to you and other than being linked to app's access, doesn't have to mean anything.
Provide a way for each API implementer to open an account with you. This way you will know who is accessing what and in some cases you can block/stop service.
For instance, a token can just be an MD5 hash:
7f138a09169b250e9dcb378140907378
In the database, this hash is linked to their account. On each request, they send this token with what they want. It is verified first to be valid, then the request is fore filled. If the token is invalid, then you can decide how to deal with it. Either don't return anything or return an "access denied" (or anything you want).
One thing to avoid is having a single token for everyone, though this can be a starting point. The reason for this is if some unauthorized app gets a hold of this token and exploits it, you have to change the token for everyone, not just the app that somehow leaked the token. You also can't control if someone has access to something or not.
Since you listed ASP.NET, I can also point you to WCF, which is fairly complex but has all the tools that you need to setup a comprehensive web service to service both you and your clients.
I hope this gives you a starting point!
EDIT:
There are security concerns here in the case that someone leaks their token key somehow. Make sure that you setup a way in which the app/your service do not expose the the token in anyway. Also have a flexible way of blocking a token, both by your clients in you, if it so happens that a token is exploited.

Implementing 2-legged OAuth to get user specific data for use in Javascript

I am diving into OAuth 2.0 to protect my RESTful services. I own the consumer and the provider sides, and therefore do not need the end-user to allow access to the data on the provider. I've experimented with client credentials flow, but this appears to only allow me to get a token for my whole client, but not for an individual user. If I used the token for my client in Javascript, then it would be given to all users and wouldn't be very secure because users could potentially get data for all other users.
Is there a way that I can use 2-legged (aka client credentials) to get a user-specific token that can be used in Ajax/Javascript (similar to what the implicit flow provides, but without user approval)?
Thanks.
You're right, the standard says nothing about user credentials for the "client credentials grant" scenario. However, if the protected resources belong to users, each token should be related to a specific user. Based on your question, I think this is the case.
If you're implementing the OAuth server, too, then you can easily do this. Just add a "user_id" parameter to the authorization request in the "client credentials grant" scenario. Processing the request on the server side, you can tie the token to the specified user. You may consider this as your own slight extension to the protocol.
You may also want to be completely standard-comformant and do nothing that's not written in stone, or you may not have access to the OAuth server implementation. In this case, you may try to use user-agnostic tokens (or "whole client" tokens as you called them in your question). However, accessing the protected resource, you must explicitly specify the user (e.g. as part of the resource path or in a query parameeter using HTTP) since it cannot be deduced from the token itself.
I discovered the ability to auto-approve clients, so the user does not have to authorize when certain clients access their data. This works in my scenario because I am using the same single sign-on mechanism for both websites, and the login to the provider is transparent to the user.

How can I design a javascript API that allows for cross-domain scripting securely?

I like the way Google Maps' api is consumed, using a script include, but I'm worried:
My api is "semi-private", that is, accessible over the internet but should allow for secure transmission of data and some kind of authentication. The data should remain private over the wire, and one consumer shouldn't be able to get at another's data.
How can I use SSL and some kind of authentication to keep the data secure, but still accessible "horizontally" from a plain HTML page with no server-side proxy required? Do I need to manage keys? How will the keys be posted to the server without being intercepted? Can I use OpenId (or some other 3rd-party authentication) to authenticate api users, or do I have to create my own authentication mechanism? I've been all over Google and can't find a good guide to designing and deploying my API securely.
Right now I'm using REST and AJAX to consume them, but cross-domain calls are impossible. Any help or a pointer in the right direction would be much appreciated.
I'd probably use a dynamically-generated script tag with an SSL URL that included a key in the query string that was public-key encrypted. The server would use the private key to decrypt the query string parameter and return script that included the relevant information (or didn't, if the key was invalid). Or something along those lines. But I'll admit that I haven't actually had to do it in practice.
I'd also look for prior art, like Amazon's S3 service.
So:
User provides secret
Client-side code uses public key to encrypt the secret
JavaScript appends a script tag that includes the URL
Server handles the script request, decrypts the secret, checks it, and sends back the relevant response.
You may well need two cycles, because otherwise the request to the server could be re-used via a man-in-the-middle attack. That would be:
JavaScript appends a script tag that requests a unique key (probably with some confounding information, like the source IP and some random further key)
Server responds with a one-time key tied to that IP
User provides secret
Client-side code uses public key to encrypt the secret, including the unique key from #1
JavaScript appends a script tag that includes the URL
Server handles the script request, decrypts the secret, checks it, and sends back the relevant response.
The response could well be encrypted (to some degree) using the random key included in #1
None of which I've actually done. (Or have I? BWAa-ha-ha-ha...) FWIW.
OAuth might help with this situation by having the user login to the 3rd-party application and allowing your application to access the 3rd-party on their behalf by using a request token when you make xhr requests. http://oauth.net/documentation/getting-started/
========
The reason for using a server-side proxy boils down to the Same-origin policy built into web browsers: http://en.wikipedia.org/wiki/Same_origin_policy
Essentially the browser only allows requests to be made to the address in which the page comes from (e.g. facebook.com can only make requests to facebook.com URIs). A server-side proxy solves this issue by making requests to servers outside the current origin. Server-side proxies are also the best practice for making requests like this.
Check out the opensource javascript Forge project. It provides a javascript TLS implementation that allows secure cross-domain xhr requests. It might be of use to you:
http://digitalbazaar.com/2010/07/20/javascript-tls-1/
http://digitalbazaar.com/2010/07/20/javascript-tls-2/
https://github.com/digitalbazaar/forge
One potential solution:
Set up an Apache server to run your site.
Get an SSL certificate for your site.
Install the apache mod that comes with Forge to setup a cross-domain policy that allows other sites to access yours.
Host Forge's TLS implementation on your site along with your site's certificate in PEM format.
Tell other sites to include the javascript from your site and use it to make secure calls to your site to do whatever it is you want to.
(3rd party) Page uses OAUTH or something similar to authenticate the user and get a token from your server.
Page loads an IFRAME from your server via SSL passing the token along for authentication.
The IFRAME can communicate securely to your server via SSL
Use easyXDM or something similar to communicate between the IFRAME and the 3rd party page, using some limited RPC-like or socket-like API you create.
Or if you really don't trust the third party - do your authentication inside the iframe (no need for oauth then, just use a plain html form) and communicate anything the outer page needs to know about the user using easyXDM.
Not too sure of what the question is exactly, I take it you're attempting to do a jsonp-like call to [https://secure.com] in order to process/display data on [http://regular.com]?
Can the two servers talk to each other? How about something like this:
User logs in on [https://secure.com]
Upon authentication, secure.com generates an token (lets call it syntoken) and passes it directly to regular.com (server-to-server), maybe like a session_id, some arbitrary message, and an otp cipher (lets call it syncipher).
Broswer receives a session_id cookie, and Secure.com then redirects the browser to http://regular.com/setcookieandredirect?session_id=blabla&otpencryptedsynmessage=blabla
Regular.com looks up otp cipher using session_id as a key, and decrypts otpencryptedmessage "blabla."
If decrypted message matches the original message in the syntoken, we can verify user is logged in [regular.com] and regular.com generates another token (lets call it acktoken, lolz) and passes it directly to [secure.com], consisting of session_id, some arbitrary ack message, and a different otp cipher (lets call it ackcipher).
Regular.com then sends the browser a cookie consisting of otpencryptedackmessage (let's name this cookie "verified_session").
Finish loading the page.
From there, you can do jsonp-like calls to
https://secure.com/getscript.js?query=dataname&verifiedtoken=(verified_sessions_cookie_value)
where secure.com/getscript.js will take the verifiedtoken, lookup the ackcipher based on the original cookie session_id sent by [secure.com] as the key, and decrypt the otpencrypedackmessage. If the decrypted message matches the ack message, render the script file.
It's kinda like a 3-way handshake. The secret sauce is that the servers have to be able to talk to each other directly to pass secret keys discretely. You don't have to use the same session_id for both servers, I was just using that as an easy point of reference to find a way to access the syn/ack otp ciphers. The ciphers must be completely hidden from public.

Categories