# Sign In with Email/Phone Number

> **Concepts:** Learn about how [**Sign in with Email/Phone Number**](https://docs.cotter.app/features/verify-email-phone) 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](https://107069962-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0QGDMRD8y_Kd-BpOvT%2F-M0ettq-majX5NbShx97%2F-M0evnVY2weMqYHvqNDO%2Fimage.png?alt=media\&token=4c5d2e18-d3e3-42c3-a1f3-9c8877b16e99)

## Steps

1. [Import Cotter as a dependency](#step-1-import-cotter-as-a-dependency)
2. [Initialize Cotter with your API Keys](#step-2-initialize-cotter-with-your-api-keys)
3. [Register URL Scheme](#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](#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](#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.](https://docs.cotter.app/getting-access-token/verifying-jwt-tokens)
{% endhint %}

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

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 %}

## 🎉 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](https://docs.cotter.app/protecting-your-account/only-allow-your-website-app-to-use-your-api-key)
* [Rate Limit the number of authentication requests](https://docs.cotter.app/protecting-your-account/rate-limit)
* [Enable reCAPTCHA to prevent automated abuse](https://docs.cotter.app/protecting-your-account/enable-recaptcha-to-protect-against-automated-abuse)

## Next Steps

### Implement Trusted Devices

{% content-ref url="older-sdk-version/android-sdk" %}
[android-sdk](https://docs.cotter.app/sdk-reference/android/older-sdk-version/android-sdk)
{% 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 %}
