DEV Community

Cover image for How to Use Magic URL Login with Appwrite
Muthu Annamalai Venkatachalam
Muthu Annamalai Venkatachalam

Posted on • Originally published at muthuannamalai.tech

How to Use Magic URL Login with Appwrite

Magic links allow you to log in without a password. Users don't have to enter any credentials to sign in; instead, they're sent a URL with an embedded token via email, or sometimes via SMS. When a user clicks the link for authentication, they are redirected back to the application or system, having successfully logged in as if they used a "magic" password, but without revealing any actual password.

Some organizations are moving away from password-based authentication to magic logins, depending on their risk appetite. If your users want access to their Slack inbox, Tumblr inbox, or apps and services within your company, magic login allows them to avoid remembering multiple passwords.

In this post, I’ll explore how does magic link works, its advantages, and how to setup Magic URL Authentication to a Web Application using the Appwrite - Web SDK

How does the magic link work?

magic links.png

The magic login process consists of three steps:

  1. First, a user enters their email address at your sign-in page.

  2. Users will receive an e-mail with a magic link if it is a registered email address.

  3. After opening the email, the user clicks the magic link to complete the sign-in process.

If the user chooses, the system can also send them a live link that they can use to authenticate themselves later on. The process is similar to one for changing a password, where the user receives a special link that will bypass his or her password and enable the user to create a new one. In order to establish magic login, app designers must come up with a solution for removing the password (and all associated resetting ceremonies) and instead of sending the user a one-time-use link.

A developer can either configure the link to stay valid for set periods of time or for the duration of a user session. When the user clicks the link in time, they are authenticated and a cookie is set so that they remain logged in throughout the session.

The magic link method works like password resets do, except the user doesn't have to remember a password or enter it to access their account. In this way, magic links simplify login procedures and provide an optimal user experience without imposing hardware requirements.

How To Setup Magic Login in Appwrite

logo.png

I'll walk you through adding Magic URL Authentication to a Web App using the Appwrite - Web SDK. The same can be done with our Flutter SDK as well as our Android SDK.

Our first step will be to add our Web SDK to our project using NPM in the following manner:

npm install appwrite --save

Enter fullscreen mode Exit fullscreen mode

When you want to import Appwrite into a bundler (like Rollup or Webpack), do the following:

import { Appwrite } from "appwrite";

Enter fullscreen mode Exit fullscreen mode

In order to use an Appwrite service with a CDN (content delivery network), you must add the following script to your HTML file:

<script src="https://cdn.jsdelivr.net/npm/appwrite"></script>

Enter fullscreen mode Exit fullscreen mode

As the next step, you need to initialize the SDK with your project ID, which you will find in your project settings:

// Init your Web SDK
const appwrite = new Appwrite();

appwrite
    .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint
    .setProject('455x34dfkj') // Your Appwrite Project ID
;

Enter fullscreen mode Exit fullscreen mode

How To Create A Magic URL IN Appwrite

When your SDK has been set up, access the Account service and call the createMagicURLSession() method. As arguments, the method accepts an email address and a redirect URL.

// Initiate the Magic URL login
appwrite.account.createMagicURLSession('name@example.com', 'http://localhost/')
    .then(response => {
        console.log(response); // Success
    }, error => {
        console.log(error); // Failure
    });

Enter fullscreen mode Exit fullscreen mode

The user is emailed the URL containing the secret key if the createMagicURLSession() method is completed without error. Clicking on the link will redirect the user to the link URL you provided, with userId and secret key attached to it in the URL query string. After 1 hour this link will no longer be valid. By default, if the provided e-mail address does not already belong to any user, a new one will be created.

## How To Login with a Magic URL in Appwrite

We can now complete the authentication process by handling the redirect from the URL in the e-mail as the user is now in a position to begin it.

With the query strings for the secret and userId values from the URL, call the updateMagicURLSession() method.

To avoid Redirect Attacks, only the domains you specified when adding your platforms via the console will work as redirect URLs.

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
});

Enter fullscreen mode Exit fullscreen mode

A successful updateMagicURLSession() will result in the user being logged in. Once a link has been used, it cannot be used again.

Benefits of using magic links

Implementing magic links has many benefits for organizations. The following are some of these benefits:

  • Easy authentication deployment and use: Due to the near-identical flow of magic links and password resets, implementing them requires only small changes in code without incurring significant additional costs.

  • Seamless onboarding: A simple magic link allows users to register for an app with their email address, making it simple and inviting to use.

  • Reduced login troubleshooting: With magic links replacing passwords, organizations experience lower administrative costs. As a result, security alerts and new password requests will become less of a hassle.

  • High usability on a range of devices: Users can authenticate with magic links on any device that can access email, so they're equally applicable across smartphones, tablets, laptops, and desktops. Clicking on the link will authenticate the user on the device they're using. Users are naturally accustomed to opening emails on the device they're working on at the time, so this shouldn't cause any friction.

If you want to keep your customers' accounts secure without compromising a simple user experience, magic links are a great option. Is magic links the best user authentication option for your application? The answer likely depends on what the application does. It may not be a wise choice to use magic links when handling sensitive financial or health care data. If your specialty is entertainment and online shopping, you're probably all set!

Want to give magic links a try? With Appwrite, magic links are free and easy to set you up. If you have any queries regarding it you can hop in the Appwrite Discord Server and get your queries resolved.

References:

I hope that this article helped you to see how easy it is in Appwrite to add magic login methods for your customers. So what are you waiting for go and use Appwrite in your projects

Happy Appwriting ♥

You can now extend your support by buying me a Coffee.😊👇

Buy Me A Coffee

Thanks for Reading 😊

Top comments (0)