# 1. Authentication

## Using the library

`HAT-API-Android` provides features that enable your app to `authenticate` with the PDA, `read/write` to the `PDA`, fetch and setup `Data Plugs` and `Applications`, fetch `Data debits` and use advanced features like `Combinators` and `Bundles`.

## Authenticate with PDA

The `PDA` is an API-only service, meaning it does not enforce a specific Application or User Interface to expose the data to the user. Instead, authentication happens using the HAT APIs and the [Javascript Web Token](https://jwt.io) (`JWT`). Each PDA runs as a separate server and has a publicly reachable address (such as `https://postman.hubat.net`). All calls in this documentation are therefore executed against an individual PDA.

### Steps

The steps to logging in with a PDA are:

1. You send the user to `/hatlogin` endpoint on their PDA, such as `https://postman.hubat.net`.
2. The PDA owner enters their login details in the login screen and verifies the service they are logging into.
3. The user is redirected back to the address you have provided with authentication token in a query parameter. You validate the token against the PDA’s public key to confirm that the user owns the specific PDA and log them in.

## Step 1 - Redirect user to PDA Login

To log in the user with their PDA, you need to ask for their PDA address. Depending on the status of your app within the HAT ecosystem you may also have a specific `application name`, an allowed `success redirect url` and an allowed `fallback redirect url` to which the user is sent to complete authentication. If you do not have these details, you can put any `application name`, `success redirect url` and `fallback redirect url`. However, the authentication token you receive will not grant you any permissions to do any operations on the PDA; it can only verify that the token really came from the PDA.

For an `Android` application that means asking user to type the `DA Address`. Here's a very simple example:

![](/files/pIZbj0MSVf3QkoAp9IFR)

In the above image, the user is being asked to fill in the HAT address, `postman`, and select a domain, `.hubat.net`. There can be other domains as well, e.g.: `hubofallthings.net`. We thought that splitting the address and the domain made for a better UX, but this is not a requirement for your app. You could have one `EditText` that the user will have to type the full address, `postman.hubat.net`.

Having asked the user to fill in the `DA address`, e.g. `postman.hubat.net`, you have to send them to `"https://$hatAddress/#/hatlogin?name=$applicationName&redirect=$redirectURL&fallback=$fallbackRedirectURL"` endpoint of the `PDA`, where:

* `$hatAddress` is the PDA's (fully qualified domain) address, e.g. `postman.hubat.net`
* `$applicationName` is the name of your application on the HAT. This is defined once when you complete the form to create a new application. e.g `testing`
* `$redirectURL` is the URL to which the user should be sent after completing authentication. ***Optional*****.** For an `Android`application that would probably be: `$applicationName://success` and has to be added in the `AndroidManifest.xml` file of

  the project in intent-filter of an Activity as a data with `host="success"` and `scheme="$applicationName"`.
* `$fallbackRedirectURL` is the URL to which the user should be sent in case the authentication has failed. ***Optional***.

  For an `Android` application that would probably be: `$applicationName://failed` and has to be added in the `AndroidManifest.xml`file of the project in intent-filter of an Activity as a data with `host="failed"` and `scheme="$applicationName"`

In an `Android` application, in order to redirect the user to an existing `DA address` and proceed to the next step, we have to use `WebView` to open the `URL`.

To achieve this with `WebView` you have to create an xml file with `WebView` element and an activity with the login address described above, `"https://$hatAddress/#/hatlogin?name=$applicationName&redirect=$redirectURL&fallback=$fallbackRedirectURL"`, and then via a `Activity`, present the WebView layout. e.g.:

```markup
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:id="@+id/webView">
</WebView>
```

```kotlin
val mWebView = findViewById(R.id.webView)
mWebView.loadUrl(url)
```

That will launch WebView within the app and load the url specified.

## Step 2 - Logging in the User

In the next step, users will be asked to fill in the `password` for the particular `PDA Address`:

![](/files/U9iF5VB1x3WALKIOVvhw)

This screen cannot be modified in any way. Users have to insert the password for the specified PDA and tap `LOGIN`.

Note that the complete address is served via **SSL**, contains the PDA's name as well as the application parameters – `application name`, `redirect url` and `fallback redirect url`.

By tapping `LOGIN` the authentication process will begin. `PDA` will use one of the two `redirect url` that were included in the `request`; `success redirect` if everything went ok or `fallbackRedirectURL` if an error occurred. The application has to know how to respond in both scenarios.

To achieve that, we have to add the `success redirect` and `fallbackRedirectURL` to the `AndroidManifest` file in the project.

To add them to the `AndroidManifest` file, you have to add the **Key** `URL Types` as a data.

```markup
<activity name="MainActivity" >
  <intent-filter>
    <data
        android:host="hatappfailed"
        android:scheme="hatapp" />
  </intent-filter>
</activity>
```

This will be your app's url scheme. That means every time `Android` intercepts a URL starting with this value, like `test://host` will hand the process to your app, which will be responsible to either launch or not.

## Step 3 - Verifying the login

### Success callback

If the user logs in, they get redirected to the URL provided, with `token` query parameter appended and containing a `RS256-signed JWT` token, e.g.:

```bash
dataswift-sandbox://dataswift-sandboxhost?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhcHBsaWNhdGlvblZlcnNpb24iOiIxLjIuNyIsInN1YiI6IjEtT0tRdm1TdGdCZ0lKdm9mNUN6NktsMnhaYjhXMUszQmZFR28xa2dZVERCQmdLeUR0ZDBqOXp6VWRaUmlRdFloaFY2VjQ5a1g1WUlmTzE0K3lEcm1GUlwvN1RkUW1iWXNMS3BDST0iLCJhcHBsaWNhdGlvbiI6ImhhdGFwcHN0YWdpbmciLCJpc3MiOiJ0ZXN0aW5nLmh1YmF0Lm5ldCIsImV4cCI6MTU0NDA4Nzc3MiwiaWF0IjoxNTQxNDk1NzcyLCJqdGkiOiI5ZjdlN2MyOTYwMjZkNmM4ODBmN2M2ZTk0MzIzOTQ3Yzg2YmI2OGEwZTIxN2YxZmZhYWE2ZTY3NGYwYWE1ODRmOWRiMzEwNDhiZmI1ZjI4N2Y5YzU4OGM4MGNmOTlmNzJjZTUyOTcxZjU3Y2NkNzVmODUzNTg3OTcwYWM5NWQzNDZhYWNmMzY5OWVkN2IyYmIyMDY5ZTJiMmM5YjE1OTg2Mjc5ZGNiYTNlMTMwYjRkMTdkNTI0ZTVkMmE5MTYyZTUzM2JjNWRlODJmNDBjNTg2ZDc2ODk2MTU0NDE3NzBkOGMwNDRlZjhhNjFlNWM3Y2JkZGQzOWFmYmQ1MDllMjU2In0.i4W_pbOVP9Qb-kkNaari-2U1eWfPSZ6QfYubb6r2SzN1VK0xRe_YT6Zm8gIuEoq8mf5p9wKPcsqzgJwLe27rGNTypCI9qZhVGqY0bNEC5GaXjH3YCXGI_hRKfHiqGbRD8XN1uhOlyWJg0pw_7DA4hdy1pGapw11Pu10y1-YMy6dlieAAU3ot87OGSr5bpXi3P3Wzgvv_QHRRn0ZVXHwp9p1UvG8LFkfzAg5lPqwQGZwMhqmp2NKSF_pStmzcKIsox_1ogrfam_3cm7p1iSRPMROYWxU9rwaOLQiXYXHuB1kO9Z62vxRJLySX_1PunWwXohbu4Rw7biBvpTdLI9D_DQ
```

The token will decode to something like this:

The Header:

```javascript
{
  "typ": "JWT",
  "alg": "RS256"
}
```

The Payload:

```javascript
{
  "applicationVersion": "1.2.7",
  "sub": "1-FgW7/lhAajlonnWAr7g3yB7eByYVkiV8O3UzsFPhEkoOYdr+bbeGeATwKyZUM6YenuUQb85G+PIijAxmP85GRnTIX6bdOdeJuuw=",
  "application": "hatappstaging",
  "iss": "postman.hubat.net",
  "exp": 1543692303,
  "iat": 1541100303,
  "jti": "1c73175cd84624efb3ead7ea21fb055ae6f95a519722d314927f251dd13d19aac438861c441ef255a33dae1e1762ee914070251998cbc723a1e2f03f47784470cf70bb6aa003e582e0226d5d8a116af362d9e522a9b29b8281ab2014cc3ae4808e55a6e4752634b3f5b4c4a37e105f57695c6def44e77a2db8e5c9f36a768749"
}
```

The key parts of the Payload are:

* The `applicationVersion`, the version of the app on HAT
* The `sub` (subject), the subject of the token
* The `application`, the application name that requested the token
* The `iss` (issuer), which is the address of the PDA that has created the token and that you should be logging in
* The `exp` (expiry) time of the token as a Unix timestamp, defining whether the token is still valid
* The `iat` (issued at time) time that the token has been created as a Unix timestamp, defining whether the token is still valid. Token expires after 30 days of the issued at date, no matter if a refreshed token has been received from PDA.&#x20;
* The `jti` (JWT ID) the ID of the token

The Signature, which is generated from the token and the private key of the PDA. The signature must be verified to verify that the token has not been tampered with. A PDA’s public key can be accessed at the `/publickey` endpoint of the PDA (e.g. `https://postman.hubat.net/publickey`). The precise handling of tokens with asymmetric keys will depend on your library; however you need to make sure that your library supports `RS256` keys.

[jwt.io](https://jwt.io) contains a very useful tool for token debugging while in development as well as listing all the major JWT libraries that you can use in your project.

When you have received a successful redirect from `PDA`, you can check with `HAT API Android` and verity the user. To do so you simply have to call:

```kotlin
HATService().loginToHATAuthorization(
            applicationName: Auth.serviceName,
            url: url,
            success: success,
            failed: failed)
```

* `applicationName` is the name of the application that sent the user to log in
* `url` is the full url that returned from the `PDA`, like the example at the beginning of step 3.
* `success` is a callback to execute when the library has successfully authorised the user. You can use this callback to dismiss `WebView` activity, save the values needed and navigate to the next `Activity`.
* `failed` is a callback to execute when the library couldn't authorise the user. You can use this callback to dismiss `WebView`activity and show an error message to the user.

Having received the success callback you have to save the token, **ALWAYS** use `Encryption` to save the token. **DO NOT** save it in any non-encrypted database. It's also a good idea to save the full `PDA Address`, as you will need it many times to communicate with the PDA. You can store the values in SharedPreferences in Private mode.

As soon as you save the token you are free to navigate to your next `Activity`.

### Fail callback

If the authentication fails, you will be redirected to the fallback url. In that case you should dismiss `WebView` Activity and then update the UI or show an error message back to the user.

You can dismiss the browser from the viewController that presented originally the `Activity`, like this:

```kotlin
finish()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.dataswyft.com/build/advanced-topics/pda-authentication/password-management/tutorials/android-kotlin/1.-authentication.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
