Magic URL login with Android + Appwrite
Tags: opensource, tutorial, news, android
Published: 2021-09-09 10:35:42

Appwrite 0.10 recently released and along with it came a new authentication method; **Magic URL**. Using this new method, a user is able to create an account from a link sent to their e-mail, without providing a password.

This feature is especially useful if you want to provide a password-less authentication process for your application.

![Frame 31](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t6ihlqfjpssc83a22wc3.png)
 

## ⚙️ Setup

Let's learn how we can add Magic URL Authentication to an Android Application using the Appwrite [Android SDK](https://appwrite.io/docs/getting-started-for-android). The same can be done with the Appwrite [Web SDK](https://appwrite.io/docs/getting-started-for-web) or [Flutter SDK](https://appwrite.io/docs/getting-started-for-flutter). As this feature needs to send an email, you must properly set up SMTP service in Appwrite. If you have not already, you can follow [this guide to set up SMTP](https://dev.to/appwrite/30daysofappwrite-getting-started-with-smtp-1e2e) in your Appwrite server.

## 👷 Setup Appwrite's Android SDK

Appwrite's Android SDK is hosted on Maven Central, so you'll first need to add the `mavenCentral()` repository to your project's `build.gradle` file (if it's not already present).

```groovy
allprojects {
    repositories {
        google()
        mavenCentral()
    }
}
```

Then add the dependency to your app's `build.gradle(.kts)` file.

```groovy
implementation("io.appwrite:sdk-for-android:0.2.0")
```

The next step is to initialize your SDK [`Client`](https://github.com/appwrite/sdk-for-android/blob/main/library/src/main/java/io/appwrite/Client.kt) and [`Account`](https://github.com/appwrite/sdk-for-android/blob/main/library/src/main/java/io/appwrite/services/Account.kt) service with your project ID which can be found in your project settings page:

```kotlin
val client = Client(context)
        .setEndpoint("http://localhost/v1") // Your Appwrite Endpoint
        .setProject("[YOUR_PROJECT_ID]") // Your Appwrite Project ID
        
val account = Account(client)
```

Finally, add the following activity to your **AndroidManifest.xml** file to handle the redirection after handling the login with magic URL as follows:

 ```xml
<activity android:name="io.appwrite.views.CallbackActivity" >
    <intent-filter android:label="android_web_auth">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="appwrite-callback-[PROJECT_ID]"  />
    </intent-filter>
</activity>
 ```

## 🎩 Create a Magic URL

Once your SDK is set up, you can create a new **magic URL** using the function [`createMagicURLSession()`](https://appwrite.io/docs/client/account?sdk=android-kotlin#accountCreateMagicURLSession). This function accepts an e-mail address and an optional redirect URL as arguments.

```kotlin
// Initiate the Magic URL login
val response = account.createMagicURLSession("email@example.com")
val json = response.body?.string()
```

If the [`createMagicURLSession()`](https://appwrite.io/docs/client/account?sdk=android-kotlin#accountCreateMagicURLSession) method completes without error, the request sends the user an email with a URL containing a secret `key` for the next step. When the user clicks the link, they are redirected back to the URL you provided with the secret `key` and `userId` values attached to the URL query string. This link is valid for 1 hour. If the e-mail passed did not belong to any existing user - this request will also create a user for the passed e-mail address.

For mobile apps, you don't need to provide a redirect URL as your Appwrite instance will automatically handle the completion and redirection, and you should be redirected back to your app. For this to work you need to be able to access your Appwrite instance from your mobile; it's best to host it somewhere with a proper domain. Otherwise services such as [ngrok](https://ngrok.com/) can be used to tunnel your localhost to a temporary domain.

## 🔐 Login with a Magic URL

> If you didn't provide a redirect URL when creating your magic URL, you can skip this step.

If you do want to handle the completion of magic URL session and redirection yourself, you need to build a web app that can handle the process.

You can use the [`updateMagicURLSession()`](https://appwrite.io/docs/client/account?sdk=web#accountUpdateMagicURLSession) method and call it with the `secret` and `userId` values from the URL's query string.

> Please note that in order to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) the only valid redirect URLs are the ones from domains you have set when adding your platforms in the console interface.

 ```js
 const urlParams = new URLSearchParams(window.location.search);
 const userId = urlParams.get('userId');
 const secret = urlParams.get('secret');

 let promise = appwrite.account.updateMagicURLSession(userId, secret);

 promise.then(function (response) {
     console.log(response); // Success
 }, function (error) {
     console.log(error); // Failure
 });
 ```

If the [`updateMagicURLSession()`](https://appwrite.io/docs/client/account?sdk=web#accountUpdateMagicURLSession) succeeded, the user is now logged in. Note that once a link is used, it cannot be used again.

## 🏁 Conclusion

We hope you will enjoy this new feature of Appwrite and hope this will be useful for lots of Applications. If you need help or encounter any difficulties setting up Magic URL Login with Appwrite, please [join our Discord](https://appwrite.io/discord).

### 🔖 References

- [Appwrite Discord](https://appwrite.io/discord)
- [Getting Started with Android](https://appwrite.io/docs/getting-started-for-android)
- [Appwrite Documentation](https://appwrite.io/docs)