# Sign In with Device

### Overview

Authenticating users using Trusted Devices with Cotter's Android SDK consists of the following steps:

1. Import and Initialize Cotter
2. Calling functions to register devices a Trusted Device
3. Calling functions to authenticate from Trusted and Non-Trusted Device

### What you're building

![Trusted Devices on Cotter's Android SDK](https://107069962-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0QGDMRD8y_Kd-BpOvT%2F-M14gZQFJLVQWDQ-Emku%2F-M14tFiVaq9sa4niiIfj%2Fimage.png?alt=media\&token=8354f8fc-19e4-43ad-8d46-2f1cf5d2e9b2)

## Steps

1. [Import Cotter as a dependency](#step-1-import-cotter-as-a-dependency)
2. [Set Allowed Methods](#step-2-setting-authentication-methods) in the Dashboard to allow Trusted Devices
3. [Create a User](#step-3-creating-a-user): Create a user in Cotter by specifying your user ID.
4. [Initialize Cotter in your MainActivity](#step-4-initialize-cotter)
5. [Register current device as a Trusted Device](#step-5-register-this-device-as-a-registered-device)
6. [Authenticate from a Trusted Device](#step-6-authenticate-from-a-trusted-device)

### Step 1: Import Cotter as a dependency

Add JitPack repository your project level `build.gradle` at the end of repositories.

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

Add the Cotter's SDK as a dependency in your app level `build.gradle` .

```java
android {
  ...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  ...
  implementation 'com.github.cotterapp:android-sdk:0.3.9'
}
```

Check the latest version here <https://github.com/cotterapp/android-sdk/releases>. Then sync your gradle files.

### Step 2: Setting Authentication Methods

You need to set allowed methods for authenticating your users. To allow `TRUSTED DEVICES`, go to <https://dev.cotter.app/rules>

![Set Trusted Device as an Allowed Method](https://107069962-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0QGDMRD8y_Kd-BpOvT%2F-M1592EVZf_MTC478_zE%2F-M15A0xW-OgzjEnPqgx6%2Fimage.png?alt=media\&token=fd86e433-c49d-4324-817a-8f7a852c1450)

{% hint style="warning" %}
Remember to set the correct Project in the dropdown list
{% endhint %}

### Step 3: Creating a User

To use Cotter's sign in with device functionality, **you need to first register the user to Cotter.**

#### Registering a User to Cotter <a href="#id-1-registering-a-user" id="id-1-registering-a-user"></a>

Your server should do this request to Cotter's server **during Registration**.

{% tabs %}
{% tab title="Request" %}

```http
curl -XPOST \
-H 'API_KEY_ID: <your key id>' \
-H 'API_SECRET_KEY: <your secret key>' \
-H "Content-Type: application/json" \
-d '{"client_user_id": "<Your User Identifier (string)>"}' \
'https://www.cotter.app/api/v0/user/create'
```

{% endtab %}

{% tab title="Response" %}

```javascript
{
  "ID": "9449e9e9-00e0-4d6b-a4b6-28c5b22b0b0f",
  "created_at": "2020-01-21T12:40:21.200727668Z",
  "update_at": "2020-01-21T12:40:21.200727668Z",
  "deleted_at": null,
  "issuer": "<your key ID>",
  "client_user_id": "<Your User Identifier (string)>",
  "enrolled": [],
  "default_method": null
}
```

{% endtab %}
{% endtabs %}

Check out [Create a User API Reference](https://docs.cotter.app/api-reference/user-api#create-a-user) for full Description

### Step 4: Initialize Cotter

You can now use the SDK to enroll and verify Trusted Devices for the user you just created.

In your MainActivity, initialize Cotter with API keys, Cotter's URL to use (prod/test), and your User ID.

Production Endpoint: `https://www.cotter.app/api/v0`

```java
Cotter.init(
    this.getApplicationContext(),
    "https://www.cotter.app/api/v0",
    "<User ID>", // fill with empty string for Verify EMAIL & PHONE
    "<API_KEY_ID>",
    "<API_SECRET_KEY>" // fill with empty string for Verify EMAIL & PHONE
);
```

Example:

{% code title="MainActivity.java" %}

```java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        Cotter.init(
            this.getApplicationContext(),
            "https://www.cotter.app/api/v0",
            "hello@example.com",
            "<API_KEY_ID>",
            "<API_SECRET_KEY>");
    }
    ...
```

{% endcode %}

### Step 5: Register this device as a Registered Device

Right after your user finished their registration to your app, you should automatically register the device as a Trusted Device (or prompt your user if they want to make this device as a Trusted Device).

To enroll the current device as a TrustedDevice:

{% tabs %}
{% tab title="Java" %}

```java
TrustedDeviceHelper.enrollDevice(this, new Callback() {
    @Override
    public void onSuccess(JSONObject result) {
        Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(String error) {
        Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
    }
});
```

{% endtab %}

{% tab title="JSON result" %}

```javascript
{
  "ID": "746500ae-a5cd-4692-8fd0-49d57cf7cc57", // User ID from Cotter's system
  "created_at": "2020-02-25T04:08:26.174597Z",
  "update_at": "2020-02-27T22:20:31.333154814Z",
  "deleted_at": null,
  "issuer": "afcabd98-745f-4b9e-98de-af968d9951d3", // your API KEY ID
  "client_user_id": "1014", // you client's user ID
  "enrolled": [ // Enrolled Authentication Methods
    "PIN",
    "BIOMETRIC",
    "TRUSTED_DEVICE" // This should be added to enrolled methods once enrollDevice successful
  ],
  "default_method": "TRUSTED_DEVICE" // This will automatically be the last enrolled method, which is Trusted Device in this case
}
```

{% endtab %}
{% endtabs %}

�This method is only for the first Trusted Device. You will get an error if you attempt to enroll another Trusted Device using `enrollDevice` when there's already a Trusted Device for the account. To enroll other devices, see [Add a new Trusted Device](https://docs.cotter.app/sdk-reference/android/sign-in-with-device/add-a-new-trusted-device).

### Step 6: Authenticate from a Trusted Device

To authenticate a device, call the `TrustedDeviceHelper.requestAuth` function. This will automatically detect whether the current device is a Trusted Device or not.

{% tabs %}
{% tab title="Java" %}

```java
TrustedDeviceHelper.requestAuth(this, "<EVENT NAME>", this, Dashboard.class, new Callback() {
    @Override
    public void onSuccess(JSONObject result) {
        Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show();
        
        // Pass in the `result` to your backend server when:
        // - Logging in your users
        // - making a transaction
        // - fetching sensitive data
    }

    @Override
    public void onError(String error) {
        Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
    }
});
```

{% endtab %}

{% tab title="JSON result" %}

```javascript
{
  "ID": 1361, // Event ID
  "CreatedAt": "2020-02-27T22:22:48.705212512Z",
  "UpdatedAt": "2020-02-27T22:22:48.705212512Z",
  "DeletedAt": null,
  "client_user_id": "1014", // your client's User ID
  "issuer": "afcabd98-745f-4b9e-98de-af968d9951d3", // your API Key
  "event": "<EVENT NAME>",// requested event (LOGIN, or TRANSACTION, etc)
  "ip": "192.168.232.2", 
  "location": "Unknown",
  "timestamp": "1582842167",
  "method": "TRUSTED_DEVICE", // auth method: TRUSTED_DEVICE (other choices are PIN / BIOMETRIC)
  "new": false, // Is this a new pending event. More explanation below about Non-Trusted Device
  "approved": true, // Is this event approved.
  "signature": "oonMGCAxp3..." // Signature to make sure this event comes from Cotter's server
}
```

{% endtab %}
{% endtabs %}

�**Parameters**

```java
requestAuth(Context ctx, String event, AppCompatActivity act, Class callbackClass, Callback callback)
```

* `event`: A name to identify the event action type, like "LOGIN" or "TRANSACTION".
* `callbackClass` : The next activity class that you want to redirect to when the authentication request is finished
* `callback` : A custom Callback function that implements 2 methods: `onSuccess` and `onError`.

When an Authentication Event is requested using method `TRUSTED_DEVICE`, there are 2 possible cases:

#### Case 1: The current device is a Trusted Device

If the current device is a Trusted Device, it should automatically be approved, and you will receive a JSON result containing the requested `Event` and whether or not it's approved. The approval is based on whether or not the signature included in the request from the SDK is valid.

```java
{
  ...
  "method": "TRUSTED_DEVICE",
  "new": false, // Is this a new pending event (should be false).
  "approved": true, // Is this event approved (should be true).
  
  "oauth_token": {
    "access_token": "eyJhbGciOiJFUz...", // validate this access token
    "id_token": "eyJhbGciOiJFUz...",
    "refresh_token": "5:cYIfabtspE1cBeD7KP...",
    "expires_in": 3600,
    "token_type": "Bearer",
    "auth_method": "TRUSTED_DEVICE"
  }
}

```

You should see a result that the event is **not new**, and that it's **approved**. This is because the signature from the Trusted Device is sufficient to prove that the device is authorized.

When passing this Response to your backend, you need to check if this JSON is valid and if it comes from Cotter's server by validating the **access token**.

Checkout how to verify the OAuth Tokens from Cotter here:

{% content-ref url="../../../getting-access-token/verifying-jwt-tokens" %}
[verifying-jwt-tokens](https://docs.cotter.app/getting-access-token/verifying-jwt-tokens)
{% endcontent-ref %}

#### Case 2: The current device is NOT a Trusted Device

We'll cover this in the next guide:

{% content-ref url="android-sdk/old-authenticate-from-a-non-trusted-device" %}
[old-authenticate-from-a-non-trusted-device](https://docs.cotter.app/sdk-reference/android/older-sdk-version/android-sdk/old-authenticate-from-a-non-trusted-device)
{% endcontent-ref %}

## 🎉 You're done!

## Next Steps

{% content-ref url="android-sdk/old-authenticate-from-a-non-trusted-device" %}
[old-authenticate-from-a-non-trusted-device](https://docs.cotter.app/sdk-reference/android/older-sdk-version/android-sdk/old-authenticate-from-a-non-trusted-device)
{% endcontent-ref %}

{% content-ref url="../sign-in-with-device/add-a-new-trusted-device" %}
[add-a-new-trusted-device](https://docs.cotter.app/sdk-reference/android/sign-in-with-device/add-a-new-trusted-device)
{% endcontent-ref %}

{% content-ref url="../sign-in-with-device/customization" %}
[customization](https://docs.cotter.app/sdk-reference/android/sign-in-with-device/customization)
{% endcontent-ref %}

## Add Biometric / PIN

{% content-ref url="../android-sdk-2" %}
[android-sdk-2](https://docs.cotter.app/sdk-reference/android/android-sdk-2)
{% endcontent-ref %}
