{"info":{"_postman_id":"322a0fc2-45c0-47c4-bd8f-088f8470af41","name":"FIWARE Securing Access","description":"[![FIWARE Security](https://img.shields.io/badge/FIWARE-Security-ff7059.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAVCAYAAAC33pUlAAAABHNCSVQICAgIfAhkiAAAA8NJREFUSEuVlUtIFlEUx+eO+j3Uz8wSLLJ3pBiBUljRu1WLCAKXbXpQEUFERSQF0aKVFAUVrSJalNXGgmphFEhQiZEIPQwKLbEUK7VvZrRvbr8zzjfNl4/swplz7rn/8z/33HtmRhn/MWzbXmloHVeG0a+VSmAXorXS+oehVD9+0zDN9mgk8n0sWtYnHo5tT9daH4BsM+THQC8naK02jCZ83/HlKaVSzBey1sm8BP9nnUpdjOfl/Qyzj5ust6cnO5FItJLoJqB6yJ4QuNcjVOohegpihshS4F6S7DTVVlNtFFxzNBa7kcaEwUGcbVnH8xOJD67WG9n1NILuKtOsQG9FngOc+lciic1iQ8uQGhJ1kVAKKXUs60RoQ5km93IfaREvuoFj7PZsy9rGXE9G/NhBsDOJ63Acp1J82eFU7OIVO1OxWGwpSU5hb0GqfMydMHYSdiMVnncNY5Vy3VbwRUEydvEaRxmAOSSqJMlJISTxS9YWTYLcg3B253xsPkc5lXk3XLlwrPLuDPKDqDIutzYaj3eweMkPeCCahO3+fEIF8SfLtg/5oI3Mh0ylKM4YRBaYzuBgPuRnBYD3mmhA1X5Aka8NKl4nNz7BaKTzSgsLCzWbvyo4eK9r15WwLKRAmmCXXDoA1kaG2F4jWFbgkxUnlcrB/xj5iHxFPiBN4JekY4nZ6ccOiQ87hgwhe+TOdogT1nfpgEDTvYAucIwHxBfNyhpGrR+F8x00WD33VCNTOr/Wd+9C51Ben7S0ZJUq3qZJ2OkZz+cL87ZfWuePlwRcHZjeUMxFwTrJZAJfSvyWZc1VgORTY8rBcubetdiOk+CO+jPOcCRTF+oZ0okUIyuQeSNL/lPrulg8flhmJHmE2gBpE9xrJNkwpN4rQIIyujGoELCQz8ggG38iGzjKkXufJ2Klun1iu65bnJub2yut3xbEK3UvsDEInCmvA6YjMeE1bCn8F9JBe1eAnS2JksmkIlEDfi8R46kkEkMWdqOv+AvS9rcp2bvk8OAESvgox7h4aWNMLd32jSMLvuwDAwORSE7Oe3ZRKrFwvYGrPOBJ2nZ20Op/mqKNzgraOTPt6Bnx5citUINIczX/jUw3xGL2+ia8KAvsvp0ePoL5hXkXO5YvQYSFAiqcJX8E/gyX8QUvv8eh9XUq3h7mE9tLJoNKqnhHXmCO+dtJ4ybSkH1jc9XRaHTMz1tATBe2UEkeAdKu/zWIkUbZxD+veLxEQhhUFmbnvOezsJrk+zmqMo6vIL2OXzPvQ8v7dgtpoQnkF/LP8Ruu9zXdJHg4igAAAABJRU5ErkJgggA=)](https://www.fiware.org/developers/catalogue/)\n\n\nThis tutorial secures access to a FIWARE application using the entities created in the [previous tutorial](https://github.com/Fiware/tutorials.Roles-Permissions). The tutorial explains appropriate use of the various OAuth2 grant flows, and how to use\nthe **Keyrock** generic enabler as an Authorization Server to identify users. **Keyrock** is also used as a Policy Decision\nPoint (PDP) to restrict access.\n\nThe `docker-compose` files for this tutorial can be found on GitHub: \n\n![GitHub](https://fiware.github.io/tutorials.Securing-Access/icon/GitHub-Mark-32px.png) [FIWARE 403: Securing Access](https://github.com/Fiware/tutorials.Securing-Access)\n\n\n# Securing Access\n\n> \"When a person or party approaches your post, you should challenge them at a distance that is sufficient\n> for you to react if they turn out to have hostile intentions. You should say in a firm voice, loud enough\n> to be easily heard, *\"Halt! Who goes there?\"* (or *\"Who is there?\"*). Once the person answers, you should then say\n> *\"Advance to be recognized.\"* ... If you have identified the person or persons approaching, permit them to pass.\n> If you are not satisfied with that person's identification, you must detain the person and call the petty officer\n> of the watch.\"\n>\n>  — 11th General Order of the US Marine Corps\n\nIn order to secure access to application resources, it is necessary to know two things. Firstly, who is making the\nrequest and secondly is the requestor permitted to access the resource? The FIWARE **Keyrock** generic enabler uses\nuses [OAuth2](https://oauth.net/2/) to enable third-party applications to obtain limited access to services.\n**OAuth2** is the open standard for access delegation to grant access rights. It allows notifying a resource provider\n(e.g. the Knowage Generic Enabler) that the resource  owner (e.g. you) grants permission to a third-party\n(e.g. a Knowage Application) access to their information (e.g. the list of entities).\n\nThere are several common OAuth 2.0 grant flows, the details of which can be found below:\n\n* [Authorization Code](https://oauth.net/2/grant-types/authorization-code)\n* [Implicit](https://oauth.net/2/grant-types/implicit)\n* [Password](https://oauth.net/2/grant-types/password)\n* [Client Credentials](https://oauth.net/2/grant-types/client-credentials)\n* [Device Code](https://oauth.net/2/grant-types/device-code)\n* [Refresh Token](https://oauth.net/2/grant-types/refresh-token)\n\nThe primary concept is that both **Users**  and **Applications** must first identify themselves using\na standard OAuth2 Challenge-Response mechanism. Thereafter a user is assigned a token which they\nappend to every subsequent request. This token identifies the user, the application and the rights the\nuser is able to exercise.  **Keyrock** can then be used with other enablers can be used to limit and\nlock-down access. The details of the access flows are discussed below and in subsequent tutorials.\n\nThe reasoning behind OAuth2 is that you never need to expose your own username and password to a\nthird party to give them  full access - you merely permit the relevant access which can be either Read-Only\nor Read-Write and such access can be defined down to a granular level. Furthermore there is provision for\nrevoking access at any time, leaving the resource owner in control of who can access what.\n\nOnce the application is able to authenticate users, it is also possible to lock down access using access control\nmechanisms. Access control requires having an access policy - in other words defining who can do what.\nWe have already defined roles and permisions within the [previous tutorial](https://github.com/Fiware/tutorials.Roles-Permissions),\nand now need to programatically enforce this policy by adding in a simple\nPolicy Decision Point (PDP) – which evaluates and issues authorization decisions, and then secure access by enforcing\nthe decision using a Policy Enforcement Point (PEP).\n\n## Standard Concepts of Identity Management\n\nThe following common objects are found with the **Keyrock** Identity Management database:\n\n* **User** - Any signed up user able to identify themselves with an eMail and password. Users can be assigned\n rights individually or as a group\n* **Application** -  Any securable FIWARE application consisting of a series of microservices\n* **Organization** - A group of users who can be assigned a series of rights. Altering the rights of the organization\n effects the access of all users of that organization\n* **OrganizationRole** - Users can either be members or admins of an organization - Admins are able to add and remove users\n from their organization, members merely gain the roles and permissions of an organization. This allows each organization\n to be responsible for their members and removes the need for a super-admin to administer all rights\n* **Role** - A role is a descriptive bucket for a set of permissions. A role can be assigned to either a single user\n or an organization. A signed-in user gains all the permissions from all of their own roles plus all of the roles associated\n to their organization\n* **Permission** - An ability to do something on a resource within the system\n\nAdditionally two further non-human application objects can be secured within a FIWARE application:\n\n* **IoTAgent** - a proxy between IoT Sensors and  the Context Broker\n* **PEPProxy** - a middleware for use between generic enablers challenging the rights of a user.\n\n\n The relationship between the objects can be seen below - the entities marked in red are used directly within this tutorial:\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/entities.png)\n\n## OAuth2\n\n**Keyrock** uses [OAuth2](https://oauth.net/2/) to enable third-party applications\nto obtain limited access to services. **OAuth2** is the open standard for access delegation to\ngrant access rights. It allows notifying a resource provider (e.g. the Knowage Generic Enabler)\nthat the resource  owner (e.g. you) grants permission to a third-party (e.g. a Knowage Application)\naccess to their information (e.g. the list of entities).\n\nThere are several common OAuth 2.0 grant flows, the details of which can be found below:\n\n* [Authorization Code](https://oauth.net/2/grant-types/authorization-code)\n* [Implicit](https://oauth.net/2/grant-types/implicit)\n* [Password](https://oauth.net/2/grant-types/password)\n* [Client Credentials](https://oauth.net/2/grant-types/client-credentials)\n* [Device Code](https://oauth.net/2/grant-types/device-code)\n* [Refresh Token](https://oauth.net/2/grant-types/refresh-token)\n\nThe primary concept is that both **Users**  and **Applications** must first identify themselves using\na standard OAuth2 Challenge-Response mechanism. Thereafter a user is assigned a token which they\nappend to every subsequent request. This token identifies the user, the application and the rights the\nuser is able to exercise.  **Keyrock** can then be used with other enablers can be used to limit and\nlock-down access. The details of the access flows are discussed below and in subsequent tutorials.\n\nThe reasoning behind OAuth2 is that you never need to expose your own username and password to a\nthird party to give them  full access - you merely permit the relevant access which can be either Read-Only\nor Read-Write and such access can be defined down to a granular level. Furthermore there is provision for\nrevoking access at any time, leaving the resource owner in control of who can access what.\n\n\n# Prerequisites\n\n## Docker\n\nTo keep things simple both components will be run using [Docker](https://www.docker.com). **Docker** is a\ncontainer technology which allows to different components isolated into their respective environments.\n\n* To install Docker on Windows follow the instructions [here](https://docs.docker.com/docker-for-windows/)\n* To install Docker on Mac follow the instructions [here](https://docs.docker.com/docker-for-mac/)\n* To install Docker on Linux follow the instructions [here](https://docs.docker.com/install/)\n\n**Docker Compose** is a tool for defining and running multi-container Docker applications. A\n[YAML file](https://raw.githubusercontent.com/Fiware/tutorials.Identity-Management/master/docker-compose.yml) is used\nconfigure the required services for the application. This means all container services can be brought up in a single\ncommand. Docker Compose is installed by default as part of Docker for Windows and  Docker for Mac, however Linux users\nwill need to follow the instructions found  [here](https://docs.docker.com/compose/install/)\n\n## Cygwin\n\nWe will start up our services using a simple bash script. Windows users should download [cygwin](http://www.cygwin.com/) to provide a\ncommand line functionality similar to a Linux distribution on Windows.\n\n# Architecture\n\n\nThis application adds OAuth2-driven security into the existing Stock Management and Sensors-based application\ncreated in [previous tutorials](https://github.com/Fiware/tutorials.IoT-Agent/) by using the data created in the first [security tutorial](https://github.com/Fiware/tutorials.Identity-Management/) and reading it programatically. It\nwill make use of three FIWARE components - the [Orion Context Broker](https://fiware-orion.readthedocs.io/en/latest/),the [IoT Agent for UltraLight 2.0](http://fiware-iotagent-ul.readthedocs.io/en/latest/) and integrates the use of the [Keyrock](http://fiware-idm.readthedocs.io/) Generic enabler. Usage of the Orion Context Broker is sufficient for an application to qualify as *“Powered by FIWARE”*.\n\nBoth the Orion Context Broker and the IoT Agent rely on open source [MongoDB](https://www.mongodb.com/) technology to keep persistence of the information they hold. We will also be using the dummy IoT devices created in the [previous tutorial](https://github.com/Fiware/tutorials.IoT-Sensors/). **Keyrock** uses its own [MySQL](https://www.mysql.com/) database.\n\nTherefore the overall architecture will consist of the following elements:\n\n* The FIWARE [Orion Context Broker](https://fiware-orion.readthedocs.io/en/latest/) which will receive requests using [NGSI](https://fiware.github.io/specifications/OpenAPI/ngsiv2)\n* The FIWARE [IoT Agent for UltraLight 2.0](http://fiware-iotagent-ul.readthedocs.io/en/latest/) which will receive southbound requests using [NGSI](https://fiware.github.io/specifications/OpenAPI/ngsiv2) and convert them to  [UltraLight 2.0](http://fiware-iotagent-ul.readthedocs.io/en/latest/usermanual/index.html#user-programmers-manual) commands for the devices\n* FIWARE [Keyrock](http://fiware-idm.readthedocs.io/) offer a complement Identity Management System including:\n    * An OAuth2 authentication system for Applications and Users\n    * A website graphical front-end for Identity Management Administration\n    * An equivalent REST API for Identity Management via HTTP requests\n* The underlying [MongoDB](https://www.mongodb.com/) database :\n    * Used by the **Orion Context Broker** to hold context data information such as data entities, subscriptions and registrations\n    * Used by the **IoT Agent** to hold device information such as device URLs and Keys\n* A [MySQL](https://www.mysql.com/) database :\n    * Used to persist user identities, applications, roles and permissions\n* The **Stock Management Frontend** does the following:\n   * Displays store information\n   * Shows which products can be bought at each store\n   * Allows users to \"buy\" products and reduce the stock count.\n   * Allows authorized users into restricted areas\n* A webserver acting as set of [dummy IoT devices](https://github.com/Fiware/tutorials.IoT-Sensors) using the [UltraLight 2.0](http://fiware-iotagent-ul.readthedocs.io/en/latest/usermanual/index.html#user-programmers-manual) protocol running over HTTP - access to certain resources is restricted.\n\n\nSince all interactions between the elements are initiated by HTTP requests, the entities can be containerized and run from exposed ports.\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/architecture.png)\n\nThe necessary configuration information for adding security to the **Stock Management Frontend**  can be found in the `context-provider` section of the associated `docker-compose.yml` file - only the relevant variables are shown below:\n\n##  Context-Provider Security Configuration\n\n```yaml\n  context-provider:\n    image: fiware/tutorials.context-provider\n    hostname: context-provider\n    container_name: context-provider\n    networks:\n      default:\n        ipv4_address: 172.18.1.7\n    expose:\n        - \"3000\"\n        - \"3001\"\n    ports:\n        - \"3000:3000\"\n        - \"3001:3001\"\n    environment:\n        - \"DEBUG=tutorial:*\"\n        - \"WEB_APP_PORT=3000\"\n        - \"KEYROCK_URL=http://localhost\"\n        - \"KEYROCK_IP_ADDRESS=http://172.18.1.5\"\n        - \"KEYROCK_PORT=3005\"\n        - \"KEYROCK_CLIENT_ID=tutorial-dckr-site-0000-xpresswebapp\"\n        - \"KEYROCK_CLIENT_SECRET=tutorial-dckr-site-0000-clientsecret\"\n        - \"CALLBACK_URL=http://localhost:3000/login\"\n```\n\nThe `context-provider` container is listening on two ports:\n\n* Port `3000` is exposed so we can see the web-page displaying the Dummy IoT devices.\n* Port `3001` is exposed purely for tutorial access - so that cUrl or Postman can make UltraLight commands\n  without being part of the same network.\n\n\nThe `context-provider` container is driven by environment variables as shown:\n\n| Key |Value|Description|\n|-----|-----|-----------|\n|DEBUG|`tutorial:*`| Debug flag used for logging |\n|WEB_APP_PORT|`3000`|Port used by web-app which displays the login screen & etc.|\n|KEYROCK_URL|`http://localhost`| This is URL of the **Keyrock** Web Front-End itself, used for redirection when forwarding users |\n|KEYROCK_IP_ADDRESS|`http://172.18.1.5`| This is URL of the **Keyrock** OAuth Communications |\n|KEYROCK_PORT|`3005` | This is the port that **Keyrock** is listening on.|\n|KEYROCK_CLIENT_ID|`tutorial-dckr-site-0000-xpresswebapp`| The Client ID defined by Keyrock for this application |\n|KEYROCK_CLIENT_SECRET|`tutorial-dckr-site-0000-clientsecret`| The Client Secret defined by Keyrock for this application |\n|CALLBACK_URL|`http://localhost:3000/login`| The callback URL used by Keyrock when a challenge has succeeded.|\n\nThe other `context-provider` container configuration values described in the YAML file have been described in previous tutorials\n\nThe separate `KEYROCK_URL` and `KEYROCK_IP_ADDRESS` are only necessary because of the simplified\nDocker containerization used within the tutorial. The `KEYROCK_URL` variable with the value  `localhost` is referring\nto the location externally exposed by the container, the `KEYROCK_IP_ADDRESS` variable refers to the same location\nbut accessed from within the Docker network. Similarly the `CALLBACK_URL` contains `localhost` as it\nis assumed that the browser will be accessed from the same machine. All of these values should be replaced\nwith appropriate proxies and DNS settings for a production environment, but production deployment is beyond\nthe scope of this tutorial.\n\n\n# Start Up\n\nTo start the installation, do the following:\n\n```console\ngit clone git@github.com:Fiware/tutorials.Securing-Access.git\ncd tutorials.Securing-Access\n\n./services create\n```\n\n>**Note** The initial creation of Docker images can take up to three minutes\n\n\nThereafter, all services can be initialized from the command line by running the [services](https://github.com/Fiware/tutorials.Securing-Access/blob/master/services) Bash script provided within the repository:\n\n```console\n./services <command>\n```\n\nWhere `<command>` will vary depending upon the exercise we wish to activate.\n\n>:information_source: **Note:** If you want to clean up and start over again you can do so with the following command:\n>\n>```console\n>./services stop\n>```\n>\n\n\n### Dramatis Personae\n\nThe following people at `test.com` legitimately have accounts within the Application\n\n* Alice, she will be the Administrator of the **Keyrock** Application\n* Bob, the Regional Manager of the supermarket chain - he has several store managers under him:\n  * Manager1\n  * Manager2\n* Charlie, the Head of Security of the supermarket chain - he has several store detectives under him:\n  * Detective1\n  * Detective2\n\n| Name       |eMail                       |Password |\n|------------|----------------------------|---------|\n| alice      | alice-the-admin@test.com   | `test`  |\n| bob        | bob-the-manager@test.com   | `test`  |\n| charlie    | charlie-security@test.com  | `test`  |\n| manager1   | manager1@test.com          | `test`  |\n| manager2   | manager2@test.com          | `test`  |\n| detective1 | detective1@test.com        | `test`  |\n| detective2 | detective2@test.com        | `test`  |\n\n\nThe following people at `example.com`  have signed up for accounts, but have no reason to be granted access\n\n* Eve - Eve the Eavesdropper\n* Mallory - Mallory the malicious attacker\n* Rob - Rob the Robber\n\n\n| Name       |eMail                       |Password |\n|------------|----------------------------|---------|\n| eve        | eve@example.com            | `test`  |\n| mallory    | mallory@example.com        | `test`  |\n| rob        | rob@example.com            | `test`  |\n\n\nTwo organizations have also been set up by Alice:\n\n| Name       | Description                         | UUID                                 |\n|------------|-------------------------------------|--------------------------------------|\n| Security   | Security Group for Store Detectives |`security-0000-0000-0000-000000000000`|\n| Management | Management Group for Store Managers |`managers-0000-0000-0000-000000000000`|\n\nOne application, with appropriate roles and permissions has also been created:\n\n| Key           | Value                                  |\n|---------------|----------------------------------------|\n| Client ID     | `tutorial-dckr-site-0000-xpresswebapp` |\n| Client Secret | `tutorial-dckr-site-0000-clientsecret` |\n| URL           | `http://localhost:3000`                |\n| RedirectURL   | `http://localhost:3000`                |\n\n\nTo save time, the data creating users and organizations from the [previous tutorial](https://github.com/Fiware/tutorials.Identity-Management) has been downloaded and is automatically persisted to the MySQL\ndatabase on start-up so the asigned UUIDs do not change and the data does not need to be entered again.\n\nTo refresh your memory about how to create users and organizations and applications, you can log in at `http://localhost:3005/idm`\nusing the account `alice-the-admin@test.com` with a password of `test`.\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/log-in.png)\n\nand look around.","schema":"https://schema.getpostman.com/json/collection/v2.0.0/collection.json"},"item":[{"name":"User Credentials Flow","item":[{"name":"OAuth Password Flow (Alice)","id":"3497d5b7-e34b-4af9-a4fb-0a7b8a2d3708","request":{"method":"POST","header":[{"key":"Authorization","value":"Basic {{Authorization}}","description":"base64 concatenation of Client Id and Client Secret"},{"key":"Content-Type","value":"application/x-www-form-urlencoded"},{"key":"Accept","value":"application/json"}],"body":{"mode":"raw","raw":"username=alice-the-admin@test.com&password=test&grant_type=password"},"url":"http://{{keyrock}}/oauth2/token","description":"To log in using the user-credentials flow send a POST request to the `oauth2/token` endpoint with the `grant_type=password`\n\n  The response returns an access code to identify the user\n\n  The access code can then be used with a GET request to the `/user` endpoint to obtain user details."},"response":[],"_postman_id":"3497d5b7-e34b-4af9-a4fb-0a7b8a2d3708"},{"name":"OAuth Password Flow (Bob)","id":"779a5a64-6db8-4258-a25b-70c742c4da88","protocolProfileBehavior":{"disableBodyPruning":true},"request":{"method":"POST","header":[{"key":"Authorization","value":"Basic {{Authorization}}","description":"base64 concatenation of Client Id and Client Secret"},{"key":"Content-Type","value":"application/x-www-form-urlencoded"},{"key":"Accept","value":"application/json"}],"body":{"mode":"raw","raw":"username=bob-the-manager@test.com&password=test&grant_type=password"},"url":"http://{{keyrock}}/oauth2/token","description":"To log in using the user-credentials flow send a POST request to the `oauth2/token` endpoint with the `grant_type=password`\n\n  The response returns an access code to identify the user\n\n  The access code can then be used with a GET request to the `/user` endpoint to obtain user details."},"response":[],"_postman_id":"779a5a64-6db8-4258-a25b-70c742c4da88"},{"name":"OAuth Password Flow (Eve)","id":"5f125e5e-3376-44da-b9cc-319bb48e2109","request":{"method":"POST","header":[{"key":"Authorization","value":"Basic {{Authorization}}","description":"base64 concatenation of Client Id and Client Secret"},{"key":"Content-Type","value":"application/x-www-form-urlencoded"},{"key":"Accept","value":"application/json"}],"body":{"mode":"raw","raw":"username=eve@example.com&password=test&grant_type=password"},"url":"http://{{keyrock}}/oauth2/token ","description":"To log in using the user-credentials flow send a POST request to the `oauth2/token` endpoint with the `grant_type=password`\n\n  The response returns an access code to identify the user\n\n  The access code can then be used with a GET request to the `/user` endpoint to obtain user details."},"response":[],"_postman_id":"5f125e5e-3376-44da-b9cc-319bb48e2109"},{"name":"Get User Details","id":"2b6aa688-9f56-4371-8c65-72d485c38172","request":{"method":"GET","header":[{"key":"Accept","value":"application/json","disabled":true}],"body":{"mode":"formdata","formdata":[]},"url":{"raw":"http://{{keyrock}}/user?access_token={{access-token-alice}}","protocol":"http","host":["{{keyrock}}"],"path":["user"],"query":[{"key":"access_token","value":"{{access-token-alice}}"}]},"description":"The access code received from a previous request can be used with a GET request to \nthe `/user` endpoint to obtain user details, for example, if the `access_token`\nused had been assigned to Alice, the username (Alice) and other user details are returned\nin the response."},"response":[],"_postman_id":"2b6aa688-9f56-4371-8c65-72d485c38172"}],"id":"892a030f-daf1-4dd8-ba9c-9faaa6ddafb4","description":"The user credentials grant flow, also known as the password grant should only be used when:\n\n* A User wants to log into an application via a web-app client\n* The web-app client is absolutely trusted\n\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/user-credentials.png)\n\nThis is the most appropriate usage within the Supermarket Tutorial Application, as the Web-App has been written by us and we can\ntrust it to pass on credentials to an instance of **Keyrock** also owned by us. As you can\nsee from the diagram, the user must type their own password into the web-app client itself\n\n\n### User Credentials - Sample Code\n\n\nThe code delegates all the OAuth2 calls to a separate library function, `oa.getOAuthPasswordCredentials()`, the user is retrieve using a separate `oa.get()` call as shown:\n\n```javascript\nfunction userCredentialGrant(req, res){\n    const email = req.body.email;\n    const password = req.body.password;\n\n    oa.getOAuthPasswordCredentials(email, password)\n    .then(results => {\n        logAccessToken(req, results.access_token);\n        return getUserFromAccessToken(req, results.access_token)\n    })\n    .then(user =>{\n        // Store User and return\n    });\n}\n```\n```javascript\nfunction getUserFromAccessToken(req, accessToken){\n    return new Promise(function(resolve, reject) {\n        oa.get(keyrockIPAddress + '/user', accessToken)\n        .then(response => {\n            const user = JSON.parse(response);\n            return resolve(user);\n         })\n        .catch(error => {\n            req.flash('error', 'User not found');\n            return reject (error)\n         });\n    });\n}\n```\n\n\n### User Credentials - Running the Example\n\nIt is possible to invoke the User Credentials grant flow programmatically, by bringing up the page `http://localhost:3000/` and filling out the user name and password form.\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/tutorial-log-in.png)\n\nThe response displays the user on the top right of the screen, details of the token are also flashed onto the screen:\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/tutorial-reponse.png)\n","event":[{"listen":"prerequest","script":{"id":"a326d505-489b-4525-8ab4-2d753c8ed0d3","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"d572e8a6-6d44-43e3-9e8e-46b6b6e62f74","type":"text/javascript","exec":[""]}}],"_postman_id":"892a030f-daf1-4dd8-ba9c-9faaa6ddafb4"},{"name":"Authorization Code Grant","item":[],"id":"cdde7ad0-8ead-499d-b3b3-f97db0258aba","description":"The Authorization Code grant flow can be used where the client (in our case the Tutorial Web-application) doesn't need\naccess to any passwords directly - it just needs to know who the user is.  With the Authorization Code grant, the\nuser is redirected to an Authorization Server such as **Keyrock**, logs in there and permits access. The response returns\nan access-code which can be exchanged for an access-token which then identifies the user.\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/authcode-flow.png)\n\nThis is an example of the sort of flow used when a third party (such as Travis-CI) asks you to log in\nusing your github account. Travis never gains access to your password, but does receive details that you\nare who you claim to be from Github.\n\n\n### Authorization Code - Sample Code\n\nA user must first be redirected to **Keyrock**, requesting a `code`:\n\n```javascript\nfunction authCodeGrant(req, res){\n    const path = oa.getAuthorizeUrl('code');\n    return res.redirect(path);\n}\n```\n\nThe after the User authorizes access, the response is handled in the code below, an access code is received from **Keyrock**\nand  second request is made to obtain a usable access token.\n\n```javascript\nfunction authCodeGrantCallback(req,res){\n    return oa.getOAuthAccessToken(req.query.code)\n    .then(results => {\n        return getUserFromAccessToken(req, results.access_token);\n    })\n    .then (user => {\n    \t// Store User and return\n    });\n}\n```\n\n### Authorization Code - Running the Example\n\nIt is possible to invoke the User Credentials grant flow programmatically, by bringing up the page `http://localhost:3000/`\nand clicking on the Authorization Code Button\n\nThe user is first is redirected to **Keyrock**, and must log in\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/keyrock-log-in.png)\n\nThe user must then authorize the request\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/keyrock-authorize.png)\n\nThe response displays the user on the top right of the screen, details of the token are also flashed onto the screen.\n\n> **Note** Unless you deliberately log out of **Keyrock** `http://localhost:3005`, the existing **Keyrock** session which has already\n> permitted access will be used for subsequent authorization request.\n\n","event":[{"listen":"prerequest","script":{"id":"0fc6ebc8-6d3b-4e72-8ee4-bba47c103a33","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"eb163ab5-78bc-4666-ad46-d4799f4752b0","type":"text/javascript","exec":[""]}}],"_postman_id":"cdde7ad0-8ead-499d-b3b3-f97db0258aba"},{"name":"Implicit Grant","item":[],"id":"af3b3ca8-1d0f-4320-901b-758a356fc4b8","description":"The Implicit grant flow is a simplified form of the Authorization grant flow where **Keyrock** returns an\naccess-token directly rather than returning an acces-code. This is less secure than the Authcode flow but\ncould be used in some client-side applications\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/implicit-flow.png)\n\n\n### Implicit Grant - Sample Code\n\nA user must first be redirected to **Keyrock**, requesting a `token`:\n\n```javascript\nfunction implicitGrant(req, res){\n    const path = oa.getAuthorizeUrl('token');\n    return res.redirect(path);\n}\n```\n\nThe after the User authorizes access, the response is handled in the code below,\na usable access token is received from **Keyrock**\n\n```javascript\nfunction implicitGrantCallback(req,res){\n    return getUserFromAccessToken(req, req.query.token)\n    .then (user => {\n        // Store User and return\n    })\n}\n```\n\n\n###  Implicit Grant - Running the Example\n\nIt is possible to invoke the Implicit grant flow programmatically, by bringing up the page `http://localhost:3000/`\nand clicking on the Implicit Grant Button\n\nThe user is first is redirected to **Keyrock**, and must log in\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/keyrock-log-in.png)\n\nThe user must then authorize the request\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/keyrock-authorize.png)\n\nThe response displays the user on the top right of the screen, details of the token are also flashed onto the screen.\n\n\n> **Note** Unless you deliberately log out of **Keyrock** `http://localhost:3005`, the existing **Keyrock** session which has already\n> permitted access will be used for subsequent authorization request.","event":[{"listen":"prerequest","script":{"id":"180e6be1-5b8c-4781-a8f4-9cf21daa96de","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"b635b904-53c2-4311-9616-7c187952f8d4","type":"text/javascript","exec":[""]}}],"_postman_id":"af3b3ca8-1d0f-4320-901b-758a356fc4b8"},{"name":"Client Credentials Grant","item":[{"name":"OAuth Client Credentials Flow","id":"e717ccf8-8f8d-43f7-9c92-6011819eeb1d","request":{"method":"POST","header":[{"key":"Authorization","value":"Basic {{Authorization}}","description":"base64 concatenation of Client Id and Client Secret"},{"key":"Content-Type","value":"application/x-www-form-urlencoded"},{"key":"Accept","value":"application/json"}],"body":{"mode":"raw","raw":"grant_type=client_credentials"},"url":"http://{{keyrock}}/oauth2/token ","description":"To log in using the client credentials flow send a POST request to the `oauth2/token` endpoint with the `grant_type=client_credentials`\n\nThe response returns an access code to identify the application itself."},"response":[],"_postman_id":"e717ccf8-8f8d-43f7-9c92-6011819eeb1d"}],"id":"7a03a43c-e747-49ed-8bc6-f6553832e3a2","description":"The final grant flow does not need a user. It is sometimes necessary for an application to identify itself\nso that the application (rather than the user) is granted access to resources. There are no\nresources secured in such a manner within this tutorial, but the flow has been included for completeness.\n\n![](https://fiware.github.io/tutorials.Securing-Access/img/client-credentials.png)\n\n### Client Credentials Grant - Sample Code\n\nThe code is similar to the User Credential Grant, but without an explicit username or password.\n\n\n```javascript\nfunction clientCredentialGrant(req, res){\n    oa.getOAuthClientCredentials()\n    .then(results => {\n       // Store Access token\n    });\n}\n```\n\n### Client Credentials Grant - Running the Example\n\nIt is possible to invoke the Client Credentials grant flow programmatically, by bringing up the page `http://localhost:3000/`\nand clicking on the Client Credentials Button\n\nThe response displays the details of the token. No User is involved.","event":[{"listen":"prerequest","script":{"id":"e871402a-6b43-435f-95ba-804ab57d0a25","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"d3268975-e320-446e-bec4-bad61cde1999","type":"text/javascript","exec":[""]}}],"_postman_id":"7a03a43c-e747-49ed-8bc6-f6553832e3a2"},{"name":"Refresh Token","item":[{"name":"Availability Check","id":"67758602-fdca-4eed-af4e-5b7c6fb3b593","request":{"method":"POST","header":[{"key":"Authorization","value":"Basic {{Authorization}}","description":"base64 concatenation of Client Id and Client Secret"},{"key":"Content-Type","value":"application/x-www-form-urlencoded"},{"key":"Accept","value":"application/json"}],"body":{"mode":"raw","raw":"username=alice-the-admin@test.com&password=test&grant_type=password"},"url":"http://{{keyrock}}/oauth2/token","description":"Check to see if Refresh Token flow is available, merely log in using one of the other grant types,\nfor example to log in using the user-credentials flow send a POST request to the `oauth2/token` endpoint\n with the `grant_type=password`\n \n Along with the `access_token` identifying the user, the response returns an `refresh_token`"},"response":[],"_postman_id":"67758602-fdca-4eed-af4e-5b7c6fb3b593"},{"name":"Refresh Access Token","id":"fc7f11a4-33ea-46e7-80b8-164194ca6bbf","request":{"method":"POST","header":[{"key":"Authorization","value":"Basic {{Authorization}}","description":"base64 concatenation of Client Id and Client Secret"},{"key":"Content-Type","value":"application/x-www-form-urlencoded"},{"key":"Accept","value":"application/json"}],"body":{"mode":"raw","raw":"username=alice-the-admin@test.com&password=test&grant_type=password"},"url":"http://{{keyrock}}/oauth2/token","description":"The  `refresh_token=05e386edd9f95ed0e599c5004db8573e86dff874` from the response above \nis stored for later use. To obtain a new `access_token`  (for example once the previous\none has expired) the `refresh_token` is used in the OAuth2 refresh token flow and a `grant_type=refresh_token`\n\n**Note** - this request will only be successful if the value of the `refresh_token` \nhas been updated."},"response":[],"_postman_id":"fc7f11a4-33ea-46e7-80b8-164194ca6bbf"}],"id":"549b4378-fac8-4fb8-91db-e12d023e7e72","description":"Once a User has identified themselves (using any appropriate grant type), they should not need to log-in again,\neven though the `access_token` they are using is time-limited. To provide continued access, an addition\n[Refresh Token](https://tools.ietf.org/html/rfc6749#section-1.5) flow has been defined, allowing a User to\nexchange an expired token for a new one. Offering this exchange is not mandatory for OAuth2 Authorization Servers,\nand is not appropriate for all grant types.","event":[{"listen":"prerequest","script":{"id":"7cdb7dc7-d4a6-4df4-8429-71f1fb556e91","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"ce4fd0e1-8c7c-467b-a78c-618a7f57432c","type":"text/javascript","exec":[""]}}],"_postman_id":"549b4378-fac8-4fb8-91db-e12d023e7e72"},{"name":"PDP-  Access Control","item":[{"name":"Resource Access (Alice)","id":"3d2d1b32-cf59-4c23-b77e-01a6fd4656a1","request":{"method":"GET","header":[{"key":"Accept","value":"application/json","disabled":true}],"body":{"mode":"formdata","formdata":[]},"url":{"raw":"http://{{keyrock}}/user?access_token={{access-token-alice}}&action={{action}}&resource={{resource}}&app_id={{app-id}}","protocol":"http","host":["{{keyrock}}"],"path":["user"],"query":[{"key":"access_token","value":"{{access-token-alice}}"},{"key":"action","value":"{{action}}"},{"key":"resource","value":"{{resource}}"},{"key":"app_id","value":"{{app-id}}"}]},"description":"If a user has logged in, the `access_token` can be used in combiniation with the `/user` endpoint\nto obtain access permissions to a resouce. This example retrieves Alice's permissions to a given\nresource."},"response":[],"_postman_id":"3d2d1b32-cf59-4c23-b77e-01a6fd4656a1"},{"name":"Resource Access (Bob)","id":"1585a9cf-4b4b-4687-92fc-4b39299e2f1a","request":{"method":"GET","header":[{"key":"Accept","value":"application/json","disabled":true}],"body":{"mode":"formdata","formdata":[]},"url":{"raw":"http://{{keyrock}}/user?access_token={{access-token-bob}}&action={{action}}&resource={{resource}}&app_id={{app-id}}","protocol":"http","host":["{{keyrock}}"],"path":["user"],"query":[{"key":"access_token","value":"{{access-token-bob}}"},{"key":"action","value":"{{action}}"},{"key":"resource","value":"{{resource}}"},{"key":"app_id","value":"{{app-id}}"}]},"description":"If a user has logged in, the `access_token` can be used in combiniation with the `/user` endpoint\nto obtain access permissions to a resouce. This example retrieves Bob-the-Manager's permissions to a given\nresource.\n\nThe response will include his role(s) within the application and whether access is pemitted or denied."},"response":[],"_postman_id":"1585a9cf-4b4b-4687-92fc-4b39299e2f1a"},{"name":"Resource Access (Eve)","id":"b4f84580-61f6-4cda-9b58-68b6fefc142c","request":{"method":"GET","header":[{"key":"Accept","value":"application/json","disabled":true}],"body":{"mode":"formdata","formdata":[]},"url":{"raw":"http://{{keyrock}}/user?access_token={{access-token-eve}}&action={{action}}&resource={{resource}}&app_id={{app-id}}","protocol":"http","host":["{{keyrock}}"],"path":["user"],"query":[{"key":"access_token","value":"{{access-token-eve}}"},{"key":"action","value":"{{action}}"},{"key":"resource","value":"{{resource}}"},{"key":"app_id","value":"{{app-id}}"}]},"description":"If a user has logged in, the `access_token` can be used in combiniation with the `/user` endpoint\nto obtain access permissions to a resouce. This example retrieves Eve's permissions to a given\nresource - no permissions have been granted.\n\nThe response will have no roles and access is denied."},"response":[],"_postman_id":"b4f84580-61f6-4cda-9b58-68b6fefc142c"}],"id":"426662c3-c75f-4a7d-888d-1b4f1803d46f","description":"If we are using our own trusted instance of **Keyrock**, once a user has signed in and obtained an `access_token`, the\n`access_token` can be stored in session and used to retrieve user details on demand. The request for user details may be extended\nto include resource permissions. Using this information it is possible to permit or deny access to individual resources.\n\nAs a reminder, **Keyrock** permissions are based on `resource` (e.g. URL) and `action` (which can be mapped to an HTTP\nverb). We can retrieve extended user details including access permisions by adding additional parameters to a `/user` GET request\n\n### Access Control - Sample Code\n\nKeyrock can therefore be used as a PDP on its own, we merely need to check if the user has access to the resource and set a flag:\n\n```javascript\nfunction accessControl (req, res , next, url=req.url){\n    const keyrockUserUrl = keyrockIPAddress + '/user' +\n        '?access_token=' +  req.session.access_token +\n        '&action='+ req.method +\n        '&resource='+ url +\n        '&app_id=' + clientId;\n    return oa.get(keyrockUserUrl)\n    .then(response => {\n        const user = JSON.parse(response);\n        res.locals.authorized = (user.authorization_decision === 'Permit' );\n        return next();\n     })\n    .catch(error => {\n        debug(error);\n        res.locals.authorized = false;\n        return next();\n    });\n}\n```\n\nA secured Web Page needs to check if the `authorized` flag has been set, and redirect the user if disallowed\n\n```javascript\nfunction priceChange(req, res) {\n\tif(!res.locals.authorized){\n\t\treq.flash('error', 'Access Denied');\n\t\treturn res.redirect('/');\n\t}\n\t/// Continue with the normal flow of execution...\n}\n```\n\nSimilarly a secured command can fail fast and return an error code if the user is not authorized,\n\n```javascript\nfunction sendCommand (req, res) {\n\tif(!res.locals.authorized){\n\t\tres.setHeader('Content-Type', 'application/json');\n\t\treturn res.status(403).send({ message: 'Forbidden' });\n\t}\n\t/// Continue with the normal flow of execution...\n```\n\n### Access Control - Running the Example\n\n> **Note** Only four resources have been secured:\n> * sending the unlock door command\n> * sending the ring bell command\n> * access to the price-change area\n> * access to the order-stock area\n\n\n#### Bob The Regional Manager\n\n* Log in as `bob-the-manager@test.com` with the password `test`\n* Click on the restricted access links at the base of the page - access is **permitted** - This is a management only permission\n* Open the Device Monitor on `http://localhost:3000/device/monitor`\n   * Unlock a door - access is **denied**. - This is a security only permission\n   * Ring a bell - access is **permitted** - This is permitted to all users\n\n#### Charlie the Security Manager\n* Log in as `security@test.com` with the password `test`\n* Click on the restricted access links at the base of the page - access is **denied** - This is a management only permission\n* Open the Device Monitor on `http://localhost:3000/device/monitor`\n   * Unlock a door - access is **permitted** - This is a security only permission\n   * Ring a bell - access is **permitted** - This is permitted to all users\n\n\n#### Anonymous Access\n\n* Ensure that you are not signed in as any user.\n* Click on the restricted access links at the base of the page - access is **denied**\n* Open the Device Monitor on `http://localhost:3000/device/monitor`\n   * Unlock a door - access is **denied**\n   * Ring a bell - access is **denied**\n\n\n#### Eve the Eavesdropper\n\nLog in as `eve@example.com` with the password `test`\n* Click on the restricted access links at the base of the page - access is **denied**\n* Open the Device Monitor on `http://localhost:3000/device/monitor`\n   * Unlock a door - access is **denied**\n   * Ring a bell - access is **denied**\n\n\n\n","_postman_id":"426662c3-c75f-4a7d-888d-1b4f1803d46f"}],"event":[{"listen":"prerequest","script":{"id":"5d5da0c2-053b-4758-8a44-e37e6534a763","type":"text/javascript","exec":[""]}},{"listen":"test","script":{"id":"9ec3f15b-4cd0-4a47-8a67-471009a09131","type":"text/javascript","exec":[""]}}],"variable":[{"key":"keyrock","value":"localhost:3005"},{"key":"Authorization","value":"dHV0b3JpYWwtZGNrci1zaXRlLTAwMDAteHByZXNzd2ViYXBwOnR1dG9yaWFsLWRja3Itc2l0ZS0wMDAwLWNsaWVudHNlY3JldA=="},{"key":"access-token-alice","value":"e233f07c18bf1f9f532b66e848c9b0128eaea304"},{"key":"access-token-bob","value":"6c1f1ac938f644c655b9c46c67d9f8b068345e89"},{"key":"access-token-eve","value":"e41786eea0c2663d8490bf41e3e0aa841e8ca2e5"},{"key":"action","value":"GET"},{"key":"resource","value":"/app/price-change"},{"key":"app-id","value":"tutorial-dckr-site-0000-xpresswebapp"},{"key":"refresh-token","value":"c64a49b2adbb659c0a7e1fe9e391544949ca0b94"}]}