Tutorial - User Authentication | Chino.io

Introduction

In this tutorial we will explore how Authentication on Chino.io works. We will see the two standard procedures that can be used to validate your calls to Chino.io and when it is better to use them.

Authentication Types

We have two acces methods: Customer Access and OAuth2:

  1. When you use Customer Access, you have full acccess to your data stored on Chino.io. You authenticate with your customer_id and customer_key that grant you admin power and no access restrictions. This access method is meant to be used only on server-side applications.

  2. With the OAuth2 you can perform logins as a specific User, thus with some limitations. The login requires the username/password along with some information about the client and, if successful, it will return you a bearer token and a refresh token. (Learn more about OAuth protocol 2.0 here .)

When choosing an authentication method for your application, you should ask yourself if you need to do anything of the following with Chino.io API:

  • Restrict access to resources stored on Chino.io,

  • Keep track of who sends API calls to Chino.io,

  • Distribute your application directly to end users (instead of hosting it on your server),

  • Verify whether your users are logged in or not.

If your answer is yes to any of the above, then you probably should use the OAuth2 authentication method. Otherwise if those features are already implemented on your system, or if you don't need them at all, the solution that uses customer credentials may better suit your needs.

Please note that you can use both the methods above in different parts of your application: the important thing is to know when and how they should (and should not) be used.

Customer Access

When you sign up to Chino.io, you are provided with a customer_id and a customer_key, which we call customer credentials: they identify a Chino.io customer and grant admin privileges on all the data in the customer's domain.

Because of the great power of customer credentials, which we'll see shortly, they must never be written in client side code (e.g. a smartphone application or a client-side javascript library): they are meant to be used by applications that run on server side, where the value of customer_id and customer_key can be kept secret and away from users.

Logs for customer's activities on Chino.io will show data of the customer whose credentials were used to authenticate the request.

Since there is no login procedure there is neither a way to identify the user who is performing the activity, nor a way to limit and control their access to the resources.

OAuth2

This authentication method relies on Chino.io User objects in order to control and keep track of activity that involves sensitive data. With Chino.io you can use the OAuth2 protocol to authenticate a User and allow him to perform actions on Chino.io.

Chino.io and the OAuth 2.0 Authorization Framework

Chino.io architecture implements the Oauth 2.0 protocol roles in the following fashion:

  • Chino.io itself can be one or both of an authorization server and a resource server

  • A User represents a physical person on Chino.io, i.e. a resource owner

  • Every software which allows Users to communicate with Chino.io by sending API calls is registered as an Application, which represents the client in OAuth 2.0

Furthermore, your architecture may include one or more servers that can play the role of client (communicating with our API) or resource server (holding non-sensitive or pseudonymized data) or both.

Chino.io combines the client_credentials authentication type (a.k.a. 2-legged OAuth) of OAuth 2.0 with a username/password pair that identifies the User: before using the API, Users must insert their credentials in an Application that has been previously registered on Chino.io. There are two types of Applications that reflect the OAuth2 protocol client types:

  • confidential clients that operate on a trusted server. These clients are identified with the application_id and application_secret parameters on Chino.io. The application_secret, being known only by the developer, adds an extra layer of security.

  • public clients that are meant to be downloaded on user's devices. E.g. mobile apps, web apps that run in the end user's browser, standalone desktop applications are all public clients. Since these applications are meant to be distributed to the public clients, thus their data can't be kept secret, the Oauth2 protocol does not require to input the application_secret; thus, this kind of Applications are only identified by their application_id.

This is a safe implementation as long as user data are sent over HTTPS, which can prevent phishing attacks and credential theft even on public clients.

Once a User logs in on Chino.io he receives a bearer token, that is needed for the authentication on Chino.io. The bearer token has an expiration time. A refresh token is also issued at login and it is used to renew the bearer token when it is about to expire.

Advantages of OAuth2

With OAuth2 you can rely on Users API to manage and access resources on Chino.io. You can:

  • rely on a solid implementation of OAuth 2.0 framework for authenticating your users, using Chino.io as an authorization server in a 2-legged OAuth2 scenario.

  • allow any authenticated User to interact with their data stored on Chino.io, while restricting access to anybody else.

  • use a solid Permissions system that allows you to control access (create, read, write, delete and more...) to your sensitive data.

  • log every action with the credentials of a registered User, whose data can be joined with your existing user management system.

This last feature lets you know where the API calls come from (from which User): the caller's data are included in the log, which can not be modified:

Code Example

Let's see some basic implementations of the two authentication methods we have just seen.

The code is available for the following programming languages: {{languages.join(", ")}}. You can change the programming language below:

Select language:

Register to Chino.io 

To register to our service go to console console, fill in the form, confirm the email and access.

If you use the test environment (strongly recommended for development since it's free) you can login with your Github account.

Write here your customer ID and Key

Here you can write your customerId and customerKey to have them filled out in the code. It's just for the purpose of the tutorial.

Click on the following button to add the Collection with the calls of this tutorial in Postman.
Postman will automatically set the values inserted in this page in the environment variables.

Note: if you want to add an environment in Postman, please fill the customer_id and customer_key in the box above.

Setup development environment

Set up the environment for the code example:

Install the SDK

First thing to do is to setup an environment (optional) and install the SDK (mandatory)

(sudo) pip install git+https://github.com/chinoio/chino-python.git

First thing to do is to setup an environment (optional) and install the SDKs (mandatory)

There are two ways to install the SDKs:

If you're using Maven, then edit your project's pom.xml and add this:

<repositories>
  <repository>
      <id>jitpack.io</id>
      <url>https://jitpack.io</url>
  </repository>
</repositories>

<dependency>
  <groupId>com.github.chinoio</groupId>
      <artifactId>chino-java</artifactId>
  <version>1.0</version>
</dependency>

If you're using Gradle, then edit your project's build.gradle and add this:

allprojects {
  repositories {
      ...
      maven {
          url 'https://jitpack.io'
      }
  }
}

dependencies {
  // ...
  compile 'com.github.chinoio:chino-java:1.0'
}

The other method is building the SDKs from source:

git clone https://github.com/chinoio/chino-java.git
cd chino-java
./gradlew build

The output will be in build/

And if you want a "fat jar" with all the dependencies inside use the following commands:

git clone https://github.com/chinoio/chino-java.git
cd chino-java
./gradlew build shadowJar

In order to perform network operations your Android manifest must include the following permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Note

Network operations in Android cannot be performed in the main UI Thread. You have to wrap the API calls in an AsyncTask :

  • Start the AsyncTask passing all the required parameters in an array: execute(params)

  • Perform your call inside the method doInBackground, which is executed asynchronously

  • Elaborate the results - if it can be done in the async method - and eventually return them

  • Update your local values and the UI in the method onPostExecute, which is executed on the UI thread.


{{ androidCode ? "Hide" : "Show" }} example

Create a subclass of AsyncTask:

Then, from your Activity or class trigger the task like this:

TextView mTextView = findViewById(R.id.myTextView); String[] params = { "68e0cfb0-bb2b-4cf1-b73a-f83e262f2ce8", "a311dea9-9486-4a05-8050-a53409b00aa4", "0dbe2671-7f74-4739-be1d-7a0db303f6bb" }; new ChinoAsyncTaskExample(mTextView).execute(params);

You can use Postman to try our rest API. We provide a Collection, to be imported in Postman, which allows you to easily test every call in this tutorial.

You can download it by clicking on this link

SDK distribution

You can integrate the CHINO.io Swift SDK into your project using one of several methods.

CocoaPods

To use CocoaPods, a dependency manager for Cocoa projects, you should first install it using the following command:

$ gem install cocoapods

Then navigate to the directory that contains your project and create a new file called Podfile. You can do this either with pod init, or open an existing Podfile, and then add

pod 'ChinoOSXLibrary', :git => 'https://github.com/chinoio/chino-ios.git', :tag => '1.0'

to the main loop. Your Podfile should look something like this:

use_frameworks!

target '<YOUR_PROJECT_NAME>' do
pod 'ChinoOSXLibrary', :git => 'https://github.com/chinoio/chino-ios.git', :tag => '1.0'
end

Then, run the following command to install the dependency:

$ pod install

Once your project is integrated with the CHINO.io Swift SDK, you can pull SDK updates using the following command:

$ pod update

Initialize SDK

First of all, you need to initialize the API client with your customer credentials:

Create a Repository

The next step is to create a Repository.

Repositories can be created via the API or via the console. For this tutorial we create a Repository via the console.

We create a Repository using Postman. All of the API requests for the Environment Setup can be found inside the Setup folder, in the Postman collection.

Note: without a Repository you can't create Schemas, and without Schemas you can't create Documents in which to store your data.

Once created we copy the (write here your repository_id) and we use it as constant in our code.

Create a Schema

The Schema represents the structure of the Document we want to store inside Chino. For this tutorial we store the following information:

  • patient_name : string (indexed) - the patient that we have visited

  • visit_type : string (indexed) - the type of the visit

  • result : text (not indexed) - the response of the visit

  • clinic_number : integer (indexed) - a number that identifies the clinic where the visit was made

Note: if the field is indexed it can be used to search for Documents. Better explanations throughout this tutorial.

Note: this is the Schema over which we are going to grant Permissions.

We call this schema base_vist

Once created, copy the schema_id

Create Document

We create manually the Document that we are going to read later in the code example:

Once created, copy the document_id

Create a UserSchema

We create a UserSchema which defines the following attributes of the Users:

  • name: string (indexed) - the name of the user

  • last_name: string (indexed) - the last name of the user

  • date_birth: date (indexed) - the date of birth of the user

  • role: text (not indexed) - the role of the user (if patient or doctor)

Once created, copy here your user_schema_id:

Create User

For this tutorial we need a User that will do the log in. Users log in with a username/password pair, which is chosen on creation.

Once created, copy the user_id

Register Application

Finally, we create an Application which represents the client the User will use to log in.

Once created, copy the application_id
and the application_secret

Note: the setup is required in order to run the code example.

Read Document with customer access

API calls made by a Customer are authenticated via Basic Auth , which we already used to create Schemas, Users, etc. during the setup. Once we set the customer credentials we are able to send API calls, e.g. to read a Document

With Customer Access we can create, read, delete anything on Chino.io and we can also grant/revoke Permissions to Users, so that they can read or edit documents. Now we let our User read the content of all the Documents in that Schema:

If you want to learn more about Permissions and how they work, check out the Chino.io docs .

Read Document with OAuth2

Before interacting with Chino.io, a User must input his credentials - username and password - in a client, that will authenticate with Chino.io using the client credentials application_id and application_secret (if needed). Here we have an example of an login call from the confidential client that we created during system setup:

If user's and client's credentials are valid, Chino.io will reply with an access token and a bearer token:

Finally, we can use the access token to read a Document; to be able to do this we need read Permission on the resource the user wants to access. Since we already granted this in the previous paragraph, the API call will return the Document's content':

Realistic Use Case

We end this tutorial with a brief example of a realistic interaction between a cloud service that relies on Chino.io for user authentication, namely Your Cloud, and a new end user that registers to the service.


  1. An end user registers to the cloud service. Your Cloud uses its own customer credentials and creates a User object on Chino.io with the end user's data, plus a username and password of user's choice.

  2. Your Cloud provides two ways to use the service: a mobile app (public client) and a web interface, which communicates directly with a service running on Your Cloud (confidential client).

  3. At first, the user attempts to log in the web app:

    • User inputs username and password in a form in the web app, then the form is sent to Your Cloud.

    • The service on the backend receives the data and issues an Auth request at Chino.io. The request contains (username, password, application_id, application_secret)

    • If the credentials are correct Chino.io responds with the auth tokens, that will be kept in Your Cloud and used in the following API calls.

  4. The user downloads the mobile app and logs in:

    • User inputs username/password in the app

    • The app sends directly to Chino.io an Auth request containing (username, password, application_id).

    • If login is successful the response from Chino.io contains the user's tokens that are stored in the user's device and used in subsequent API calls.

  5. Lastly, the user needs to download on the mobile app some data which are stored on Your Cloud, instead of being on Chino.io. Your Cloud needs to verify the user's identity before processing the request.

    • The application sends a request to Your Cloud and includes the access token it got during step 4

    • Your Cloud sends the token to Chino.io, which checks the token's validity

    • If the verification is successful, Your Cloud sends the data back to the mobile app..

Summary

We have seen three different ways to handle user authentication with Chino.io API. We have explained their purposes, pros and cons: be sure to choose the one that fits your architecture at best.