User management across multiple stateless API applications - api

We want to make our API stateless.
Right now, the tokens for users are provided via 3rd party, upon login, and stored in the application memory.
As long as the token is in use, it is valid. Until it is idle for a configurable amount of time.
On 3rd party's side (the token provider) this token is valid for much longer (For example: A month on their side regardless of usage VS. 20 minutes of idle time on ours).
Meaning, each usage of this token updates the timestamp in the application memory.
As part of making our API stateless I've encountered a problem:
Assuming we will have more than one application and a load balancer,
how do i maintain the user management between 2 applications?
I know how to restore the users profile/details if the token isn't in the application memory (but still valid on 3rd party side), but i can't know the timestamp of it's last usage.
I think that i either have to sync the cache between my applications, or manage the users on another service.
I'm hoping that my explanation is clear enough.
My questions are:
What is the best practice for this issue?
Where can i find useful information regarding user management across multiple applications? I think that i'm struggling with key words in this case.
Thanks in advance

From the architectural point of view separate user manager is preferable. In this case you will never turn to your 3rd party token provider directly but do it via your own manager that stores tokens and the timestamps. This however will probably require a serious refactoring.
So, other solution that I can offer is probably using tool that provides sharing memory among processes and machines. For example you can use Hazelcast. It is very easy to start tool with very user-friendly API. If for example you store mapping from token to timestamp in map now the only thing you have to change is the place where you create map. Use the Hazelcast map factory instead of new HashMap<>() and your tokens will be magically distributed among your applications.

Related

OAuth flow for third party API access

There is a lot of information on the web about OAuth 2, its different types of flows and where/how to use them. I find that most of these resources discuss authenticating a user for an application, but I am struggling to understand what the best/correct approach would be when consuming third party APIs (i.e. when our own API is the "middleman" between a user and their data in a third party API).
With the help of an example scenario and some diagrams, I would be really grateful for advice/opinions on how I should properly implement integration with third party APIs and what the pros & cons of each approach are.
Starting point
As a starting point, suppose we have a web app, structured as follows:
Frontend - SPA (Angular), hosted with AWS S3 + Cloudfront
Backend - Node, running as stateless AWS lambda functions with AWS API Gateway
Auth0 for handling auth/signin etc. The frontend uses an Implicit OAuth2 flow to obtain access_tokens, which are stored in local storage and included as a header in all requests to the backend.
Potentially also native mobile app(s), consuming the same backend API.
Goal
Now suppose that we wish to add integration with Google Sheets. The new feature would allow users to use their own Google Sheets (i.e. stored in their own Google account) as a data source, with the app having read&write access to the sheet. There may be other integrations in the future, so I am assuming that other APIs would require a similar process.
Problem statement
In addition to the existing OAuth process (which allows users to sign in to the "MyApp" frontend and communicate with the "MyApp API"), there needs to be an additional OAuth process for users to connect MyApp to the third party Google Sheets API.
The documentation has two Quickstart examples, but neither seems to quite fit my needs:
Browser - https://developers.google.com/sheets/api/quickstart/js
Node.js (console app) - https://developers.google.com/sheets/api/quickstart/nodejs
The data from the third-party (Google) API is one of potentially several integration points, so intuitively it seems more logical (and more secure) that all communication with the Google Sheets API should happen in the MyApp API, and not on the frontend/client side. The MyApp API would fetch data, process/manipulate/format it in some way and then present it for display in the frontend or mobile apps.
We require access to each user's own data, so the Client Credentials flow is not suitable. I am focussing on the Implicit or Authorization Grant workflows.
Important note: The trickiness seems to come from the fact that the MyApp API is stateless, so there is no long-lived session in which to store tokens. On that basis, it seems like tokens need to be stored either in the frontend (e.g. local storage/cookies etc) or in a backend database.
Below is my interpretation of two possible approaches. I'd appreciate thoughts/corrections.
Option 1: Implicit flow - tokens stored FE, passed along to BE which then makes requests to Google
Pros:
Allows access to user's own data
Simpler flow, access_token retrieved immediately without needing the code step
Less steps to implement between initial sign-in process and actually obtaining data
No need for a backend database, can resend the token with each request
Cons:
Frontend (browser) has access to Google access_token which seems unnecessary and is a potential security concern
It seems like a strange process to pass the access_token from FE to BE, purely to allow BE to then use that token to make another request
I'm not sure how we would refresh/renew tokens since I understand that storing refresh_tokens on the client is bad practice. It would not be a good user experience if the user had to frequently sign in to reconnect their account
Option 2: Authorization Code Flow - all communication with Google via BE, tokens stored in BE database
Pros:
Allows access to user's own data
Other than the code-request / consent page, all communication with Google is implemented backend, so the tokens are not accessible on the client
Client secret can be used from the BE
Cons:
More complex flow, requires extra steps
Given that the BE is stateless, it's not clear how best to store the tokens. It seems like it would require storing them in a database which is extra complication and seems like it would have security implications - how would you properly secure / encrypt the access_token/refresh_tokens in said database?
Conclusion
Given that the data processing is to happen on the backend, option 2 seems slightly more suitable because the sensitive tokens can be hidden from the frontend app, and several clients (web frontend, mobile apps) have less obligation to be involved in the process with the exception of the initial sign in / user consent. However I’m not sure whether having a database full of user auth tokens is a good idea or how I could properly protect this database.
The good news is that both options are perfectly valid and equally secure. The concern about a short-lived Access Token being in the browser isn't an issue. Equally, if you only held the tokens on the BE, then you would need to implement your own client authentiation/session/JWT blah blah, which presents the same attack surface.
I've done both, and am currently migrating from BE to FE. In my case the reason is that everything I need to do, I can do on the FE, so I end up with no BE at all. This isn't strictly true since I do some onboarding/payment with the BE, but that's about all.
So the best approach depends on factors beyond those in your question, such as the nature of app, what the BE cost is and how important that is, what your devops skillsets look like for maintaining two environments, to what extent a BE is required anyway, vs being completely optional.

Authentication: JWT usage vs session

What is the advantage of using JWTs over sessions in situations like authentication?
Is it used as a standalone approach or is it used in the session?
JWT doesn't have a benefit over using "sessions" per se. JWTs provide a means of maintaining session state on the client instead of doing it on the server.
What people often mean when asking this is "What are the benefits of using JWTs over using Server-side sessions".
With server-side sessions, you will either have to store the session identifier in a database, or else keep it in memory and make sure that the client always hits the same server. Both of these have drawbacks. In the case of the database (or other centralised storage), this becomes a bottleneck and a thing to maintain - essentially an extra query to be done with every request.
With an in-memory solution, you limit your horizontal scaling, and sessions will be affected by network issues (clients roaming between Wifi and mobile data, servers rebooting, etc).
Moving the session to the client means that you remove the dependency on a server-side session, but it imposes its own set of challenges.
Storing the token securely.
Transporting it securely.
JWT sessions can sometimes be hard to invalidate.
Trusting the client's claim.
These issues are shared by JWTs and other client-side session mechanisms alike.
JWT, in particular, addresses the last of these. It may help to understand what a JWT is:
It is a bit of information. For user sessions, you could include the username and the time when the token expires. But it could conceivably be anything, even the session ID or the user's entire profile (please don't do that though).
It has got a secure signature that prevents malicious parties from generating fake tokens (you need access to the server's private key to sign them and you can verify that they were not modified after they were signed).
You send them with every request, just like a cookie or Authorization Header would be sent. In fact, they are commonly sent in the HTTP Authorization header but using a cookie is fine too.
The token is signed and so the server can verify its origin. We will assume that the server trusts its own ability to sign securely (you should use a standard library: don't try to do it yourself, and secure the server properly).
On the issue with securely transporting the token, the answer is commonly to send it via an encrypted channel, usually httpS.
Regarding securely storing the token in the client, you need to ensure that the bad guys can't get to it. This (mostly) means preventing JS from bad web sites from reading the token to send it back to them. This is mitigated using the same strategies used to mitigate other kinds of XSS attacks.
If you have a need to invalidate JWTs, there are definitely ways this can be achieved. Storing a per-user epoch for only users who have requested to have their "other sessions terminated" is a very efficient method that will probably be good enough. If an application needs per-session invalidation, then a session ID can be maintained in the same way and the "killed tokens" table can still be maintained to be much smaller than the full user table (you only need to retain records newer than the longest allowed token lifetime). So the ability to invalidate the token partially negates the benefit of client-side sessions in that you would have to maintain this session killed state. This will more than likely be a much smaller table than the original session state table, so the lookups are still more efficient though.
One other benefit of using JWT tokens is that it is reasonably easy to implement using libraries available in probably every language you can expect to have it. It is also completely divorced from your initial user authentication scheme - if you move to a fingerprint-based system, you do not need to make any changes to the session management scheme.
A more subtle benefit: Because the JWT can carry "information" and this can be accessed by the client, you can now start doing some smart things. For example, remind the user that their session will be expiring a few days before they are logged out, giving them the option to re-authenticate, based on the expiry date in the token. Whatever you can imagine.
So in short: JWTs answers some of the questions and shortcomings of other session techniques.
"Cheaper" authentication because you can eliminate a DB round trip (or at least have a much smaller table to query!), which in turns enable horizontal scalability.
Tamper-proof client-side claims.
While JWTs does not answer the other issues like secure storage or transport, it does not introduce any new security issues.
A lot of negativity exists around JWTs, but if you implement the same security that you would for other types of authentication, you will be fine.
One final note: It is also not Cookies vs Tokens. Cookies is a mechanism for storing and transporting bits of information and can be used to store and transport JWT tokens too.
The short answer is: None.
A longer version is:
I implemented JWTs for session management after reading this recommendation in the GraphQL docs:
If you aren't familiar with any of these authentication mechanisms, we
recommend using express-jwt because it's simple without sacrificing
any future flexibility.
Implementation was indeed simple as it only added a little bit of complexity. After a while however, I (like you) started wondering what the benefits were. It turns out there are very few (or possibly none) for JWT as far as session management goes, as this blog post explains in detail:
Stop using JWT for sessions
I had a similar question choosing between JWT and token + cache for user authentication.
After reading these articles, it's clear to me the benefits JWT promises do not outpace the problems it brings. So token + cache(Redis/Memcached) is the way to go for me.
Auth Headers vs JWT vs Sessions — How to Choose the Right Auth Technique for APIs
Authentication Techniques for APIs
Stop using jwt for sessions
My two cents, which on the way add some contrast to joepie91's famous blog post.
Considering that today's (and tomorrow's) applications are (mostly) cloud native
There's an economic benefit to Stateless JWT Authentication,
which scales as the application scales:
Cloud applications incur cost with every passing second.
This cost is reduced when users no longer have to authenticate "against" a session store.
Detailed below are some factors which add to the cost of an application when not using JWT:
Database Server
Running a session store 24/7 costs money.
You can not get away with local storage / memory based solutions in the world of K8S, as pods are ephemeral.
Sticky sessions will not fare well for the exact same reason.
Storage
Storing data costs money. storing data in a SSD costs even more.
Session related operations need to be resolved quickly, so an optical drive is not an option.
I/O
Some cloud providers charge money for Disc related I/O.
Download
Circa 2022, it is safe to assume that the API and session store are separate server instances.
Some cloud providers charge for downloading information from one instance to another.
Scaling the session store
This affects all aforementioned factors.
Yet another slightly different perspective that may be useful if you are on AWS.
We had implemented PHP5.x session storage on AWS ElastiCache to centralise session storage across multiple servers.
It worked perfected until we moved to PHP7. It was difficult to configure for PHP7 and we were plagued with intermittent issues where it seemed that the session "failed/mismatched/got a bit confused" for a particular user and then they could not log in on that device until the old session expired.
We moved to using DynamoDb to store the session and no more issues. It is marginally slower but only noticeable at login (session storage) stage.
While this was going on, we implemented AWS cognito to replace our authentication and started to use the API-Gateway to deliver content via lambda python functions.
We use the PHP SDK to authenticate with Cognito and then we store the JWT in a cookie but still also use the PHP session to keep our legacy code working.
Now we have two stacks and the best of both worlds: PHP7 does it's bit and gets the main content to the user (very quickly). Then JS takes over and provides additional content using the JWT.
What I think is great about JWT is the fact that it can be passed around between these two stacks and used to authenticate the user in both cases.
Now we are wondering if it is worthwhile taking the plunge and switching over to the new JWT system entirely?
In PHP, we still use our legacy session but we also pass the token to cognito to authenticate it. It's a bit of extra security that is probably not necessary but it gives a warm cozy feeling. Then again, there are costs and maintenance with dynamoDb that could be saved.
In session authentication (or stateful authentication) you can store more data than token. But you have to store the session object somewhere and this makes the authentication centralized. Also, you need to have extra memory to store the sessions and this will give extra work to manage this memory. If your application grows, now you have to implement different designs based on your needs, implementing a session cache service, and storing the session on web application or database.
In Jwt or in general Stateless authentication, you do not store anything. You send the token with the request header. This makes it decentralized authentication. The drawback of this authentication is token revocation. Each token has an expiry time and if your token is stolen, it will be valid till it expires. You have to implement logic to minimize the risk.

User Auth in EventSourcing applications

I'm looking into crafting an app with DDD+CQRS+EventSourcing, and I have some trouble figuring out how to do user auth.
Users are intrinsically part of my domain, as they are responsible for clients. I'm using ASP.NET MVC 4, and I was looking to just use the SimpleMembership. Since logging in and authorising users is a synchronous operation, how is this tackled in an eventually consistent architecture?
Will I have to roll my own auth system where I keep denormalized auth tables on the read side? How to handle the security of this? Will I end up storing password hashes in both my event store and my view tables?
So many questions, if anyone can shed some light, I would be very thankful :)
tldr; How do you do User Auth in EventSource-applications?
Not every "Domain" or business component has to use DDD or CQRS. In most cases, user information is really cruddy, so you can usually not use DDD for that. Other domains don't really depend on the actual user. There's usually a correlation id (UserId) that gets shared by the various domains.
If using messaging in your system, one option is to register and manage users without CQRS, then send a command (RegisterUser { UserId } ). This would publish an event User Registered. Other domains can listen to this event to kick-off any workflows or ARs that are needed.
For our MVC CQRS app, we originally started off keeping all the user related information in the domain, and, like somebody mentioned, there was a RegisterUserCommand and a UserRegisteredEvent. After storing the user information in the domain, that event got published and picked up on the read side, which also created a user and generated all the password hashes, etc. We then done the authentication on the read side: the controller would make a call out to a 'read model authentication service' to authenticate against.
Later on down the road, we ended up completely refactoring this. It turned out that we needed access to the user related information to build in security for authorising our commands, which we done on the command processing side (our app is a distributed app that sends 'fire and forget' asynchronous commands to a queue, with an autonomous listener on the other side). The security component then needed a reference to our domain to go and get the user profile, which led to cumbersome referencing issues.
We decided to put the user security stuff into a separate database that we considered to be more of a central component, rather than belonging to the domain or read model. We still maintain user profile related information in the domain and read models (e.g. job title, twitter account URL etc.), but all the security related stuff, like password hashes, are stored in this central database. That's then accessible with a service, that's available to both MVC and the command authoriser.
We didn't actually have to change anything in the UI for this refactor, as we just called the service to register the users from the register user command handler. If you're going to do it that way, you need to be careful here to make your user service related operations idempotent. This is so that you can give your commands the opportunity to be retried without side effects, because you're updating 2 sources of information (the ES and the user database).
Finally, you could of course use the membership providers for this central component, but there can be pitfalls with that. We ended up just writing our own - it's pretty simple to do. That article links to this, which provides a good example of how to implement it.
You should consider creating separate entities like: visitor (just visited your site), user (registered), customer (bought something), etc. Try to split your system in this way, even if it causes a little bit of data redundancy. Disk space is not an issue but ability to modify different components of the system independently is usually very critical.
People create denormalized auth tables only for the purpose of scaling and only if your auth read side is a performance bottleneck. If not - usual 3rd normal form is a way to go.
In SimpleMembership scenario all tables created by SimpleMembership can be viewed as snapshot of "user" aggregate. And yes, they will duplicate some data in your event store.
You may have events like: UserCreated, UserUpdated, UserAssignedToRole, etc.
And don't be tricked by the name of that membership provider. It's not so simple and usually has lots of things that you can easily live without (depends on your domain). So, maybe you can use something like this: https://gist.github.com/Kayli/fe73769f19fdff40c3a7

Creating an API for mobile applications - Authentication and Authorization

Overview
I'm looking to create a (REST) API for my application. The initial/primary purpose will be for consumption by mobile apps (iPhone, Android, Symbian, etc). I've been looking into different mechanisms for authentication and authorization for web-based APIs (by studying other implementations). I've got my head wrapped around most of the fundamental concepts but am still looking for guidance in a few areas. The last thing I want to do is reinvent the wheel, but I'm not finding any standard solutions that fits my criteria (however my criteria my be misguided so feel free to critique that as well). Additionally, I want the API to be the same for all platforms/applications consuming it.
oAuth
I'll go ahead and throw out my objection to oAuth since I know that will likely be the first solution offered. For mobile applications (or more specifically non-web applications), it just seems wrong to leave the application (to go to a web-browser) for the authentication. Additionally, there is no way (I am aware of) for the browser to return the callback to the application (especially cross-platform). I know a couple of apps that do that, but it just feels wrong and gives a break in the application UX.
Requirements
User enters username/password into application.
Every API call is identified by the calling application.
Overhead is kept to a minimum and the auth aspect is intuitive for developers.
The mechanism is secure for both the end user (their login credentials are not exposed) as well as the developer (their application credentials are not exposed).
If possible, not require https (by no means a hard requirement).
My Current Thoughts on Implementation
An external developer will request an API account. They will receive an apikey and apisecret. Every request will require at minimum three parameters.
apikey - given to developer at regisration
timestamp - doubles as a unique identifier for each message for a given apikey
hash - a hash of the timestamp + the apisecret
The apikey is required to identify the application issuing the request. The timestamp acts similarly to the oauth_nonce and avoids/mitigates replay attacks. The hash ensures that request was actually issued from the owner of the given apikey.
For authenticated requests (ones done on the behalf of a user), I'm still undecided between going with an access_token route or a username and password hash combo. Either way, at some point a username/password combo will be required. So when it does, a hash of several pieces of information (apikey, apisecret, timestamp) + the password would be used. I'd love feedback on this aspect. FYI, they would have to hash the password first, since I don't store the passwords in my system without hashing.
Conclusion
FYI, this isn't a request for how to build/structure the API in general only how to handle the authentication and authorization from solely within an application.
Random Thoughts/Bonus Questions
For APIs that only require an apikey as part of the request, how do you prevent someone other than the apikey owner from being able to see the apikey (since sent in the clear) and make excessive requests to push them over usage limits? Maybe I'm just over thinking this, but shouldn't there be something to authenticate that a request was verified to the apikey owner? In my case, that was the purpose of the apisecret, it is never shown/transmitted without being hashed.
Speaking of hashes, what about md5 vs hmac-sha1? Does it really matter when all of the values are hashed with with sufficiently long data (ie. apisecret)?
I had been previously considering adding a per user/row salt to my users password hash. If I were to do that, how could the application be able to create a matching hash without knowing the salt used?
The way I'm thinking about doing the login part of this in my projects is:
before login the user requests a login_token from the server. These are generated and stored on the server on request, and probably have a limited lifetime.
to login the application calculates the hash of the users password, then hashes the password with the login_token to get a value, they then return both the login_token and the combined hash.
The server checks the login_token is one that it has generated, removing it from its list of valid login_tokens. The server then combines its stored hash of the user's password with the login_token and ensures that it matches the submitted combined token. If it matches you have authenticated your user.
Advantages of this are that you never store the user's password on the server, the password is never passed in the clear, the password hash is only passed in the clear on account creation (though there may be ways around this), and it should be safe from replay attacks as the login_token is removed from the DB on use.
That's a whole lot of questions in one, I guess quite a few people didn't manage to read all the way to the end :)
My experience of web service authentication is that people usually overengineer it, and the problems are only the same as you would encounter on a web page. Possible very simple options would include https for the login step, return a token, require it to be included with future requests. You could also use http basic authentication, and just pass stuff in the header. For added security, rotate/expire the tokens frequently, check the requests are coming from the same IP block (this could get messy though as mobile users move between cells), combine with API key or similar. Alternatively, do the "request key" step of oauth (someone suggested this in a previous answer already and it's a good idea) before authenticating the user, and use that as a required key to generate the access token.
An alternative which I haven't used yet but I've heard a lot about as a device-friendly alternative to oAuth is xAuth. Have a look at it and if you use it then I'd be really interested to hear what your impressions are.
For hashing, sha1 is a bit better but don't get hung up about it - whatever the devices can easily (and quickly in a performance sense) implement is probably fine.
Hope that helps, good luck :)
So what you're after is some kind of server side authentication mechanism that will handle the authentication and authorisation aspects of a mobile application?
Assuming this is the case, then I would approach it as follows (but only 'cos I'm a Java developer so a C# guy would do it differently):
The RESTful authentication and authorisation service
This will work only over HTTPS to prevent eavesdropping.
It will be based on a combination of RESTEasy, Spring Security and CAS (for single sign on across multiple applications).
It will work with both browsers and web-enabled client applications
There will be a web-based account management interface to allow users to edit their details, and admins (for particular applications) to change authorisation levels
The client side security library/application
For each supported platform (e.g.
Symbian, Android, iOS etc) create a
suitable implementation of the
security library in the native
language of the platform (e.g. Java,
ObjectiveC, C etc)
The library
should manage the HTTPS request
formation using the available APIs
for the given platform (e.g. Java
uses URLConnection etc)
Consumers of the general authentication and
authorisation library ('cos that's
all it is) will code to a specific
interface and won't be happy if it
ever changes so make sure it's very
flexible. Follow existing design
choices such as Spring Security.
So now that the view from 30,000ft is complete how do you go about doing it? Well, it's not that hard to create an authentication and authorisation system based on the listed technologies on the server side with a browser client. In combination with HTTPS, the frameworks will provide a secure process based on a shared token (usually presented as a cookie) generated by the authentication process and used whenever the user wishes to do something. This token is presented by the client to the server whenever any request takes place.
In the case of the local mobile application, it seems that you're after a solution that does the following:
Client application has a defined Access Control List (ACL) controlling runtime access to method calls. For example, a given user can read a collection from a method, but their ACL only permits access to objects that have a Q in their name so some data in the collection is quiety pulled by the security interceptor. In Java this is straightforward, you just use the Spring Security annotations on the calling code and implement a suitable ACL response process. In other languages, you're on your own and will probably need to provide boilerplate security code that calls into your security library. If the language supports AOP (Aspect Oriented Programming) then use it to the fullest for this situation.
The security library caches the complete list of authorisations into it's private memory for the current application so that it doesn't have to remain connected. Depending on the length of the login session, this could be a one-off operation that never gets repeated.
Whatever you do, don't try to invent your own security protocol, or use security by obscurity. You'll never be able to write a better algorithm for this than those that are currently available and free. Also, people trust well known algorithms. So if you say that your security library provides authorisation and authentication for local mobile applications using a combination of SSL, HTTPS, SpringSecurity and AES encrypted tokens then you'll immediately have creditibility in the marketplace.
Hope this helps, and good luck with your venture. If you would like more info, let me know - I've written quite a few web applications based on Spring Security, ACLs and the like.
Twitter addressed the external application issue in oAuth by supporting a variant they call xAuth. Unfortunately there's already a plethora of other schemes with this name so it can be confusing to sort out.
The protocol is oAuth, except it skips the request token phase and simply immediately issues an access token pair upon receipt of a username and password. (Starting at step E here.) This initial request and response must be secured - it's sending the username and password in plaintext and receiving back the access token and secret token. Once the access token pair has been configured, whether the initial token exchange was via the oAuth model or the xAuth model is irrelevant to both the client and server for the rest of the session. This has the advantage that you can leverage existing oAuth infrastructure and have very nearly the same implementation for mobile/web/desktop applications. The main disadvantage is that the application is granted access to the client's user name and password, but it appears like your requirements mandate this approach.
In any case, I'd like to agree with your intuition and that of several other answerers here: don't try to build something new from scratch. Security protocols can be easy to start but are always hard to do well, and the more convoluted they become the less likely your third-party developers are to be able to implement against them. Your hypothetical protocol is very similar to o(x)Auth - api_key/api_secret, nonce, sha1 hashing - but instead of being able to use one of the many existing libraries your developers are going to need to roll their own.
Super late to the party but I wanted to throw in some additional points to consider for anyone interested in this issue. I work for a company doing mobile API security solutions (approov) so this whole area is definitely relevant to my interests.
To start with, the most important thing to consider when trying to secure a mobile API is how much it is worth to you. The right solution for a bank is different to the right solution for someone just doing things for fun.
In the proposed solution you mention that a minimum of three parameters will be required:
apikey - given to developer at registration
timestamp - doubles as a unique identifier for each message for a given apikey
hash - a hash of the timestamp + the apisecret
The implication of this is that for some API calls no username/password is required. This can be useful for applications where you don't want to force a login (browsing in online shops for example).
This is a slightly different problem to the one of user authentication and is more like authentication or attestation of the software. There is no user, but you still want to ensure that there is no malicious access to your API. So you use your API secret to sign the traffic and identify the code accessing the API as genuine. The potential problem with this solution is that you then have to give away the secret inside every version of the app. If someone can extract the secret they can use your API, impersonating your software but doing whatever they like.
To counter that threat there are a bunch of things you can do depending on how valuable the data is. Obfuscation is a simple way to make it harder to extract the secret. There are tools that will do that for you, more so for Android, but you still have to have code that generates your hash and a sufficiently skilled individual can always just call the function that does the hashing directly.
Another way to mitigate against excessive use of an API that doesn't require a login is to throttle the traffic and potentially identify and block suspect IP addresses. The amount of effort you want to go to will largely depend upon how valuble your data is.
Beyond that you can easily start getting into the domain of my day job. Anyway, it's another aspect of securing APIs that I think is important and wanted to flag up.

Licenses and sessions the RESTful way

This question crossed my mind after I read this post:
“Common REST Mistakes: Sessions are irrelevant”
If sessions are indeed discouraged in a RESTful application. How would you handle licenses in such application. I'm specifically referring to concurrent licenses model and not named licenses. i.e. the customer buys X licenses which means the application may allow up to X users to be logged in simultaneously. Which means that the application must hold a state for current logged in users.
I know I can create a resource called licenses, which will set a cookie or generate a unique ID, and then the client will have to send it with every request. But it's the same as creating a session, right?
If I'll adopt the stateless approach and ask the client to create an authentication token for every request how will the application know when to consume and release license for that client?
Is there an alternative? specifically a more RESTful alternative?
Let me try to connect the dots for you, assuming I interpreted your question correctly.
The link you posted has a valid answer, each request should use a HTTP auth. If you need the concept of licences to maintain a certain state for your user, you can most likely link that to the user. You have a (verified) username to go by. You just need to invoke that controller for each request and save its state. There you have your session.
Cookie input should never be trusted for any critical information, but can be very useful for extra verification like a security token. I think adding a random security token field to your on-site links would be the restful approach to that. It should expire with the 'session', of course.
You may want to consider pushing the license handling concerns down the infrastructure stack one level. Sort of like an Aspect Oriented Programming (AOP) approach if you will. Instead of handling it in the application tier, perhaps, you can push it in to the web server tier.
Without knowing the details of your infrastructure, it is hard to give a specific recommendation. Using the *nix platform as an example, the license handling logic can be implemented as a module for Apache HTTP server.
This approach promotes a separation of concerns across your infrastructure stack. It allows each layer to focus on what it is meant to. The application layer does not need to worry about licensing at all, allowing it to focus strictly on content, which in turn keeps the URL's clean and "RESTful".
If your licensing is based on concurrent users, implementing HTTP digest is trivial, and will let you enable only the maximum number of concurrent logins. Digest has provision for passing expiration data so your session can be timed-out.
Authentication state is hold by http authetnication and nowhere else, beause it is transparent and ubiquituous.
Maybe a more RESTful way of doing licenses would be to limit the rate at which requests are handled, rather than the number of concurrent sessions. Keep track of the number of requests in the last hour, and if it exceeds the number the customer has paid for, serve a 503 Service Unavailable response, along with some text suggesting the user try again later.