viernes, 27 de mayo de 2016

RAML: THE RESTFUL API MODELING LANGUAGE (PART 8)

Security:


Chances are your API is secured in some way – be it using OAuth, access tokens or simply just HTTP Basic Authentication.
In RAML you can define your security schemes towards the top of your file, alongside the basic information. You’ll find some examples in the specification document, but as an example let’s look at OAuth2. Here’s what the security scheme definition might look like:
securitySchemes:
  - oauth_2_0:
      description: |
        Acme uses OAuth2 to authenticate most requests
      type: OAuth 2.0
      describedBy:
        headers:
          Authorization:
            description: |
              Used to send a valid OAuth 2 access token. Do not use
              with the "access_token" query string parameter.
            type: string
        queryParameters:
          access_token:
            description: |
              Used to send a valid OAuth 2 access token. Do not use together with
              the "Authorization" header
            type: string
        responses:
     400:
            description: |
              Bad OAuth request (e.g. wrong consumer key, bad nonce, expired
              timestamp, etc.)
          401:
            description: |
              Bad or expired token. To fix it, re-authenticate the user.          
      settings:
        authorizationUri: https://acme.com/oauth/authorize
        accessTokenUri: https://acme.com/oauth/token
        authorizationGrants: [ code, token ]
If you look through this, you’ll see it provides a number of key pieces of information;
  • The type indicates that we’re implementing OAuth 2.0
  • To authenticate, the API in question expects either an Authorization header or an access_tokenquery parameter
  • It lists the possible responses, what they mean and how to fix them
  • The settings are specific to OAuth but nonetheless vital; it tells users how to authorize, where to obtain an access token and the OAuth grant types this API supports.
However, this simply defines the security schemes; we still need to indicate that this is what we’re using to secure our API.
One way is to add the following towards the top of your RAML file:
securedBy: [oauth_2_0]
Some APIs, however, make some endpoints publicly available, but others may be protected. You can define the security approach on a per-endpoint basis, for example:
/albums:
 get:
  securedBy: [null, oauth_2_0]
 post:
  securedBy: [oauth_2_0]
Here we’re indicating that authentication is optional for retrieving a list of albums, but that a user must be authenticated in order to create one.

1 comentario: