Authentication

From Ocean Framework Documentation Wiki
Jump to: navigation, search

Authentications for the same ApiUser are re-used and thus share the same token for the duration of the authentication. This is specified in the ApiUser and defaults to three hours.

Clients have two basic options:

  1. To simply fire requests to API endpoints through a client-side interface layer which intercepts 400 and 419 responses by authenticating via a POST (and maybe only then interface with the end user, who will get a "login when needed" experience), then retrying the operation, maybe taking further action, and then passing the results back to the caller.
  2. To authenticate pro-actively using a POST, then use the token received in all subsequent accesses.

In either case, it's a good idea to have an Ocean API interface layer which handles the inevitable 400 and 419 responses by re-authenticating transparently and retrying the original operation. It should also retry after 500 and 504 and have a strategy for 503 responses. All retries should involve increasing backoffs.

The Authentication resource has two public URLs. (For information about the difference between Public and Internal URLs and HATEOAS conventions, please see API Structure and Conventions.)

The first one is the main one:

/v1/authentications

Make a POST to this URL to create an authentication for an existing ApiUser. You should not include an X-API-Token header.

The second one is used mainly by CronJobs:

/v1/authentications/cleanup

Please note that you should not draw any conclusions from the perceived structure of these or any other URLs, nor should you construct URLs based upon any inferences you make. For more information, refer to API Structure and Conventions.

Structure

token
(String) The Authentication Token to include in the X-API-Token header in all subsequent API requests.
max_age
(Integer) The number of seconds the authentication and its token are valid. The ApiUser's authentication_duration attribute is used to set this value. HTTP cache time values for authorisations are calculated accordingly.
username
(String) The username of the ApiUser for which this authentication was made.
right
(Array) This attribute is used by the ocean-rails gem to restrict access to only those parts of a table matching these two attributes (which must be present in the schema).
group_names
(Array of Strings) The names of all groups the ApiUser belongs to. Used for making resource representations include or omit attributes depending on the privileges of the ApiUser.
created_at
(String) A datetime string in GMT.
expires_at
(String) A datetime string in GMT.
{"authentication": {
   "token": "kxueHvZ5EFs07Q_er-rQErOnhvM",
   "max_age": 1800,
   "username": "aleister_crowley",
   "right": [{"app":"evocation","context":"goetia"}]
   "group_names": ["Great Beasts", "Superusers"],
   "created_at": "2012-12-09T21:26:09Z",
   "expires_at": "2012-12-09T21:56:09Z",
   "_links": {
       "self": {
         "href": "https://api.example.com/v1/authentications/kxueHvZ5EFs07Q_er-rQErOnhvM",
         "type": "application/json" },
       "creator": {
         "href": "https://api.example.com/v1/api_users/4d33adee-d5db-4a32-a288-0499e43eb44d",
         "type": "application/json" }
   }
 }
}

Hyperlinks

The following hyperlink names are used in the following subsections. To retrieve the URL and Content-Type to use, use the _links hash. Note that the URI may change, and thus you should make no inference on how to construct similar URIs from any previous URI. For more information, refer to Hyperlink URIs are Opaque. You may store hyperlink URIs in permanent storage for later use.

The hyperlinks for an Authentication resource are:

self
As always, the self hyperlink can be used to perform CRUD actions on the Authentication resource. The GET method is particularly relevant, as it is used for authorisation. POST is used to create new Authentications. PUT isn't relevant as Authentications are read-only. The DELETE method deletes an Authentication and invalidates its authorisations.
creator
The ApiUser who created this Authentication. Ocean services may use this for access restriction purposes (ocean-rails controller actions make it available in @auth_api_user_uri).


GET self

Performs authorisation. The query is passed as query args. As this is a GET request, the results will be cached. The format of the URL is as follows:

GET https://api.example.com/v1/authentications/<token>?query=<query>

The <token> is the token attribute from the Authentication resource obtained after a successful authentication POST request. It typically looks like kxueHvZ5EFs07Q_er-rQErOnhvM.

Bottle.jpg NOTE: You should not include an X-API-Token header. Including the X-API-Token header will reduce the cacheability of the response, as Varnish has been programmed to include the X-API-Token header in its hash algorithm. All caching, incuding Authorisations, is therefore per token, and Ocean re-uses tokens whenever possible.

The query is a string representing the operation for which you are seeking authorisation. It is in the format

service:resource:hyperlink:verb:app:context

The fields have the following meanings:

  • service The service, e.g. cms.
  • resource The resource in plural form, e.g. texts.
  • hyperlink The hyperlink, e.g. self. NB: self refers to the basic resource itself, the one that usually takes all verbs.
  • verb The HTTP verb, e.g. GET. Must be one of GET, GET*, POST, PUT, or DELETE. The seemingly non-standard verb GET* represents a GET of the basic collection of resources. It's only a convention used for authorisation operations visavi Rights; GET* is never used as an actual HTTP method.
  • app The application, e.g. webshop_common. An asterisk means all applications.
  • context The context within the application, e.g. cms. An asterisk means all contexts.

The query string

cms:texts:self:GET*:*:*

represents a request to obtain authorisation to get collections of Text resources from the CMS Service, for all applications and all contexts within those applications.

cms:texts:self:DELETE:webshop_common:*

represents a request to obtain authorisation to destroy any and all Text resources belonging to the webshop_common application.

auth:api_users:connect:PUT:*:*

represents a request to obtain authorisation to connect ApiUser resources to other resources. To get authorisation for the complementary disconnection operation:

auth:api_users:connect:DELETE:*:*
200
Authorisation granted. The body of the response contains the Authentication for which this authorisation was made.
400
The token is unknown. Reauthenticate with the Auth service to obtain a new token and retry the operation. If the client is a user agent, this should be done without notifying the user.
403
Authorisation denied.
419
The X-API-Token has expired. Reauthenticate and retry the operation.
422
The query string is missing or malformed.

DELETE self

Deletes an Authentication. This immediately invalidates all authorisations done using its token. This is the same thing as logging out.

Shark.jpeg WARNING: Do not DELETE an Authentication created for an ApiUser which is shared between different service consumers. If you do, all clients sharing that token will have to reauthenticate (transparently). As most use cases involving shared tokens don't involve logouts, this is rarely a problem.
204
The delete operation was successful.

POST /v1/authentications

Returns an Authentication to supply an ApiUser with a valid authentication token to use for subsequent authorisations. The token should be re-used until it expires – under no circumstances should you create a new authentication for each API request, or small group of API requests. Your code must always be prepared to handle 400 and 419 responses and re-authenticate transparently to the user.

Authentications for the same ApiUser are re-used and thus share the same token for the duration of the authentication. This is specified in the ApiUser and defaults to three hours.

The body of the POST request should be empty. You should not include an X-API-Token header in the request, but the POST must include the header

X-API-Authenticate: **********

where the asterisks represent the Base64 encoded value of the ApiUser's username and password combined like this:

username:password

To give an example, encoding the username magneto and the password xavier in this way should yield the Base64 value

bWFnbmV0bzp4YXZpZXI=
201
The operation was successful and a new Authentication resource has been created. The response headers will not include a standard Location header giving the URL of the newly created resource. Thus this 201 is not a redirect. Instead, our API returns the new Authentication resource in the response body. This is necessary as it wouldn't be possible to redirect to the GET URL, as that method is used in order to make authorisation requests cacheable. The resource contains an attribute called token which is the Authentication Token to use as the value in X-API-Token headers in subsequent requests to the API. NB: the token can expire at any time as tokens are re-used; therefore, the client application must always be prepared to re-authenticate transparently when receiving a 419 when using the token, even the very first time.
400
You didn't include an X-API-Authenticate header.
403
Your credentials are unknown or don't match.
Bottle.jpg NOTE: Do not create a new Authentication for each API request. You should re-use the Authentication and its token until it expires or you DELETE it.

Authenticating on behalf of someone else

A client may sometimes need to create an Authentication for someone else. This would be the case when a web client is to log in a user to a member-specific website area or function; in this case the web client would make the initial API calls using its own credentials. When the user wants to log in, the web client authenticates on their behalf, and then uses the resulting Authentication token in all requests to the API. Finally, the user logs out and the client creates another Authentication as itself and resumes operation.

When authenticating (as distinct from authorising), you should not include an X-API-Token header.

PUT /v1/authentications/cleanup

Purges outdated Authentications from the database.

204
The operation was successful. No body is returned.