# Sign In with Email/Phone Number

> **Concepts:** Learn about how [**Sign in with Email/Phone Number**](/features/verify-email-phone.md) works.

### Overview

Verifying **email and phone number** in your mobile app using our Android SDK consists of the following steps:

1. Import Cotter
2. Call Cotter's Login function
3. Receive user's email or phone number, and whether or not it's verified

### What you're building

![Cotter's Android SDK](/files/-M0evnVY2weMqYHvqNDO)

## Steps

1. [Import Cotter as a dependency](/sdk-reference/android/android-sdk-1.md#step-1-import-cotter-as-a-dependency)
2. [Initialize Cotter with your API Keys](/sdk-reference/android/android-sdk-1.md#step-2-initialize-cotter-with-your-api-keys)
3. [Register URL Scheme](/sdk-reference/android/android-sdk-1.md#step-3-register-a-url-scheme): Cotter's authentication will redirect back to your application using this URL scheme.
4. [Call Cotter's Login function](/sdk-reference/android/android-sdk-1.md#step-4-call-cotters-login-function): This function will handle the WebView, verifying phone number or email, and request the identity from Cotter's server.
5. [Receive the Token](/sdk-reference/android/android-sdk-1.md#step-5-receive-the-token): Include the returned token and email/phone number in your server

### Step 1: Import Cotter as a dependency

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

{% code title="build.gradle" %}

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

{% endcode %}

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.0'
}
```

Check the latest version here <https://github.com/cotterapp/android-sdk/releases>.

Then sync your gradle files.

### Step 2: Initialize Cotter with your API keys

Initialize Cotter with your `API_KEY_ID` . Call the function below in your MainActivity

```java
 Cotter.init(this.getApplicationContext(), 
         "https://www.cotter.app/api/v0",
         <API_KEY_ID>);
```

For 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",
            <API_KEY_ID>);
    }
    ...
```

{% endcode %}

### Step 3: Register a URL Scheme

You also need to decide a callback URL scheme that you want to use. If your app's package name is `com.example.myapplication` then you should use something like this for your URL Scheme callback.

```
com.example.myapplication://auth_callback
```

{% hint style="warning" %}
Make sure your URL scheme (the front part before `://`) doesn't have an underscore or other special characters. To test it out, enter your Redirect URL here: <https://jsfiddle.net/omd02jn5/>
{% endhint %}

&#x20;This URL scheme will be called when Cotter's verification is done and want to go back to your app. Read more about[ Android deep-linking.](https://developer.android.com/training/app-links/deep-linking)

You need to register this URL Scheme to receive the callback. Add the following in your `AndroidManifest.xml` . Check the example in the [example's Github repo](https://github.com/cotterapp/android-example/blob/master/app/src/main/AndroidManifest.xml).

{% code title="AndroidManifest.xml" %}

```markup
<!--   ADD THE LINES FROM HERE    -->
<activity android:name="com.cotter.app.RedirectUriReceiverActivity" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        
        <!--   This example is for: com.example.myapplication://auth_callback    -->
        <!--   Change it to your own url    -->
        <data android:scheme="com.example.myapplication" 
                android:host="auth_callback"/>
    </intent-filter>
</activity>
<!--   TO HERE    -->
```

{% endcode %}

### Step 4: Call Cotter's Login function

To open up Cotter's Login screen, you can either have your user input their email or phone number inside Cotter's screen, or you can provide a text input where your users can enter their email / phone, and you can pass that to Cotter's screen.

a) To login and enter the email or phone number in Cotter's window:

```java
 // Provide Context and the URL Scheme
 Cotter.newIdentity(this, "com.example.myapplication://auth_callback")
    .login(
        "EMAIL",             // EMAIL or PHONE
        this,                // Context
        Dashboard.class);    // Callback Class
```

b) �To login with the email or phone number that your user entered in your app:

```java
// Provide Context and the URL Scheme
 Cotter.newIdentity(this, "com.example.myapplication://auth_callback")
    .loginWithInput( // Context
       "EMAIL",                     // EMAIL or PHONE
       input.getText().toString(),  // User's email
       this,                        // Context
       CallbackActivity.class);     // Callback Class
```

{% hint style="info" %}
To send code/link via SMS or WhatsApp, you'll need to add some balance to you project in the [Dashboard](https://dev.cotter.app/).
{% endhint %}

You need to provide a class to redirect to when Cotter's email/phone number verification is complete.

{% hint style="success" %}
**Try it now!** You can check if it works so far by invoking the login function above on a button click. It should load Cotter's Authentication page on a WebView.
{% endhint %}

### Step 5: Receive the Token

In your `CallbackActivity` class, receive the token from the `intent` inside `onCreate` using this function.

```java
String resp = IdentityManager.handleResponse(getIntent());
if (resp != null) {
    Log.i("Login Response: ", resp);
}
String error = IdentityManager.handleError(getIntent());
if (error != null) {
    Log.i("Login Error: ", error);
}
```

For example, if your `CallbackActivity` class is called `Dashboard`:

```java
public class Dashboard extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        
        // Handle response here
        String resp = IdentityManager.handleResponse(getIntent());
        if (resp != null) {
            Log.i("Login Response: ", resp);
        }
        
        // Handle error here 
        String error = IdentityManager.handleError(getIntent());
        if (error != null) {
            Log.i("Login Error: ", error);
        }
    }
}
```

The `resp` will consist of the following JSON Object as a string.

```javascript
{
  "identifier": {
    "ID": "f4286df9-a923-429c-bc33-5089ffed5f68",
    "created_at": "2020-07-21T22:53:21.211367Z",
    "updated_at": "2020-07-21T22:53:21.211367Z",
    "deleted_at": "0001-01-01T00:00:00Z",
    "identifier": "putri@cotter.app", // User's email
    "identifier_type": "EMAIL",
    "device_type": "BROWSER",
    "device_name": "Mozilla/5.0 (Linux; Android 9; Android SDK built for x86 Build/PSR1.180720.075) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
    "expiry": "2020-08-20T22:53:21.19705Z",
    "timestamp": "2020-07-21T22:53:21.19705Z"
  },
  "oauth_token": {
    "access_token": "eyJhbGciOiJFUz...", // Validate this access token
    "id_token": "eyJhbGciOiJFUzI1...",
    "refresh_token": "27944:lb31DY5pG229n...",
    "expires_in": 3600,
    "token_type": "Bearer",
    "auth_method": "OTP"
  },
  "token": {...},
  "user": {
    "ID": "643a42c7-316a-4abe-b27e-f4d0f903bfea", // Cotter uesr ID
    "identifier": "putri@cotter.app",
    ...
  }
}
```

This JSON object contains 3 objects, `identifier` , `oauth_token` and `user` .&#x20;

* The identifier object contains information about the user's email or phone number, device type and name, and expiry.
* The `oauth_token` contains an `access_token` that you can validate in your backend.
* The `user` contains the User object in Cotter, which includes a "Cotter User ID". **You should associate your user with this Cotter User ID for reference.**

{% hint style="success" %}
You should include this JSON Object into your call to your backend for **Login** or **Registration**. Your backend should then verify that [the access token is valid.](/getting-access-token/verifying-jwt-tokens.md)
{% endhint %}

## Validating Cotter's Access Token&#x20;

Checkout how to verify the OAuth Tokens from Cotter here:

{% content-ref url="/pages/-M4HZPVawEx2QN3qLmnv" %}
[Verifying JWT Tokens](/getting-access-token/verifying-jwt-tokens.md)
{% endcontent-ref %}

## 🎉 You're done!

## Securing your Project

Since you'll be using your API Key from a front-end website or mobile app, your `API_KEY_ID` is exposed to anyone inspecting your code. Here are some ways to prevent abuse:

* [Only allow your website/app to use your API Key](/protecting-your-account/only-allow-your-website-app-to-use-your-api-key.md)
* [Rate Limit the number of authentication requests](/protecting-your-account/rate-limit.md)
* [Enable reCAPTCHA to prevent automated abuse](/protecting-your-account/enable-recaptcha-to-protect-against-automated-abuse.md)

## Next Steps

### Implement Trusted Devices

{% content-ref url="/pages/-M14g3WtD4o3ZG9N2j9G" %}
[Sign In with Device](/sdk-reference/android/older-sdk-version/android-sdk.md)
{% endcontent-ref %}

### Add Biometric/PIN

{% content-ref url="/pages/-M0RaVb\_ggDYyCQyIUXy" %}
[Biometric/Pin](/sdk-reference/android/android-sdk-2.md)
{% endcontent-ref %}


---

# 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.cotter.app/sdk-reference/android/android-sdk-1.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.
