<!-- llms.txt: https://workos.com/llms.txt -->
<!-- feedback.md: https://workos.com/docs/feedback.md -->

# Magic Link

> **Deprecated:** Magic Link is not recommended due to issues with email clients or other security software visiting the links and invalidating them. Instead, use [Magic Auth](https://workos.com/docs/authkit/magic-auth), which provides a more secure passwordless authentication method.

## Introduction

Managing password authentication entails significant overhead for engineering teams and opens up many risks for breaches. Magic Link from WorkOS gives you the ability to build a secure passwordless authentication flow utilizing email. Send users a one-time-use link and let them sign in with a single click.

> Magic Link sets you up to handle Single Sign-On via the [WorkOS SSO API](https://workos.com/docs/sso). The redirect URI / profile retrieval process is identical between Magic Link and SSO.

![Diagram showing Magic Link flow which emphasizes that WorkOS does not manage the session.](https://images.workoscdn.com/docs/guides/magic-link/v1/magic-link-diagram.png?auto=format\&fit=clip\&q=50)\[border=false]

Magic Link is not a session management solution – instead it is an authentication solution. You as the developer have the ability to manage user sessions as you see fit. This means you determine how long a session is valid for, as well as how to store and invalidate a session.

Magic Links are single use, meaning that they will immediately expire after they are first clicked. If end users have security checks included with their email provider that test all embedded URLs, it can cause the Magic Links to expire before they reach the user's inbox. To work around this, we recommend that end users add these Magic Link emails to an allowlist in order to bypass these security checks.

## What you'll build

In this guide, we'll take you from learning about passwordless authentication all the way through to building production-ready passwordless authentication flows with the WorkOS Magic Link API.

This guide will show you how to:

1. Add Magic Link to your app
2. Configure a redirect URI
3. Create a new Magic Link Connection

## Before getting started

To get the most out of this guide, you'll need:

- A [WorkOS account](https://dashboard.workos.com/)

## API object definitions

[Passwordless Session](https://workos.com/docs/reference/magic-link/passwordless-session)
: Represents a passwordless authentication session.

[Profile](https://workos.com/docs/reference/sso/profile)
: Represents an authenticated user. The Profile object contains information relevant to a user in the form of normalized and raw attributes.

## (1) Add Magic Link to your app

### Install the WorkOS SDK

WorkOS offers native SDKs in several popular programming languages. Choose a language below to see instructions in your application's language.

Install the SDK using the command below.

:::code-group{title="Install the WorkOS SDK"}

```bash language="js" title="npm" tab="js-1"
npm install @workos-inc/node
```

```bash language="js" title="Yarn" tab="js-2"
yarn add @workos-inc/node
```

```bash language="ruby" title="Terminal" tab="ruby-5"
gem install workos
```

```rb language="ruby" title="Bundler" tab="ruby-6"
gem "workos"
```

```bash language="python"
pip install workos
```

```bash language="go"
go get github.com/workos/workos-go/v10
```

```bash language="php"
composer require workos/workos-php
```

```bash language="laravel"
composer require workos/workos-php-laravel
```

```xml language="java" title="Maven" tab="java-3"
<dependency>
  <groupId>com.workos</groupId>
  <artifactId>workos</artifactId>
  <version>{version}</version>
</dependency>
```

```groovy language="java" title="Gradle" tab="java-4"
dependencies {
  implementation 'com.workos:workos:VERSION'
}
```

```bash language="dotnet"
nuget install WorkOS.net
```

```elixir language="elixir"
def deps do
  [{:workos, "~> 3.1"}]
end
```

```bash language="rust"
cargo add workos
```

:::

### Set secrets

To make calls to WorkOS, provide the API key and, in some cases, the client ID. Store these values as managed secrets, such as `WORKOS_API_KEY` and `WORKOS_CLIENT_ID`, and pass them to the SDKs either as environment variables or directly in your app's configuration based on your preferences.

```plain title="Environment variables"
WORKOS_API_KEY='sk_example_123456789'
WORKOS_CLIENT_ID='client_123456789'
```

### Add a callback endpoint

Let's first add the redirect endpoint which will handle the callback from WorkOS after a user has authenticated via a magic link. This endpoint should exchange the authorization code (valid for 10 minutes) returned by WorkOS with the authenticated user's Profile.

:::code-group{title="Callback Endpoint"}

```ts language="js" title="Next.js" tab="js-1"
import type { NextApiRequest, NextApiResponse } from 'next';
import { WorkOS } from '@workos-inc/node';

const workos = new WorkOS(process.env.WORKOS_API_KEY);
const clientId = process.env.WORKOS_CLIENT_ID;

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { code } = req.query;

  const { profile } = await workos.sso.getProfileAndToken({
    code,
    clientId,
  });

  // The user's organization ID
  const organization = 'org_123';

  // Validate that this profile belongs to the organization used for authentication
  if (profile.organizationId !== organization) {
    return res.status(401).send({
      message: 'Unauthorized',
    });
  }

  // Use the information in `profile` for further business logic.

  res.redirect('/');
};
```

```js language="js" title="Express" tab="js-2"
const express = require('express');
const { WorkOS } = require('@workos-inc/node');

const app = express();
const workos = new WorkOS(process.env.WORKOS_API_KEY);
const clientId = process.env.WORKOS_CLIENT_ID;

app.get('/callback', async (req, res) => {
  const { code } = req.query;

  const { profile } = await workos.sso.getProfileAndToken({
    code,
    clientId,
  });

  // The user's organization ID
  const organization = 'org_123';

  // Validate that this profile belongs to the organization used for authentication
  if (profile.organizationId !== organization) {
    return res.status(401).send({
      message: 'Unauthorized',
    });
  }

  // Use the information in `profile` for further business logic.

  res.redirect('/');
});
```

```rb language="ruby" title="Rails" tab="ruby-3"
require "workos"

WORKOS = WorkOS::Client.new(
  api_key: ENV["WORKOS_API_KEY"],
  client_id: ENV["WORKOS_CLIENT_ID"]
)

def callback
  profile_and_token = WORKOS.sso.get_profile_and_token(
    code: params["code"]
  )

  profile = profile_and_token.profile

  # The user's organization ID
  organization = "org_123"

  # Validate that this profile belongs to the organization used for authentication
  if profile.organization_id != organization
    render json: {error: "Unauthorized", status: 401}.to_json
  end

  sign_in_and_redirect profile

  # Use the information in `profile` for further business logic.
end
```

```rb language="ruby" title="Sinatra" tab="ruby-4"
require "sinatra"
require "workos"

workos = WorkOS::Client.new(
  api_key: ENV["WORKOS_API_KEY"],
  client_id: ENV["WORKOS_CLIENT_ID"]
)

get "/callback" do
  profile_and_token = workos.sso.get_profile_and_token(
    code: params["code"]
  )

  profile = profile_and_token.profile

  # The user's organization ID
  organization = "org_123"

  # Validate that this profile belongs to the organization used for authentication
  if profile.organization_id != organization
    halt 401, "Unauthorized"
  end

  redirect "/"

  # Use the information in `profile` for further business logic.
end
```

```py language="python" title="Django" tab="python-5"
from django import redirect
from django.core.exceptions import PermissionDenied
from workos import WorkOSClient

workos_client = WorkOSClient(
    api_key="sk_example_123456789", client_id="client_123456789"
)


def callback(request):
    code = request.GET["code"]
    profile_and_token = workos_client.sso.get_profile_and_token(code)

    profile = profile_and_token.profile

    # The user's organization ID
    organization = "org_123"

    # Validate that this profile belongs to the organization used for authentication
    if profile.organization_id != organization:
        raise PermissionDenied

    # Use the information in `profile` for further business logic.

    return redirect("/")
```

```py language="python" title="Flask" tab="python-6"
from flask import Flask, redirect, request
from workos import WorkOSClient

workos_client = WorkOSClient(
    api_key="sk_example_123456789", client_id="client_123456789"
)

app = Flask(__name__)


@app.route("/callback")
def callback():
    code = request.args.get("code")
    profile_and_token = workos_client.sso.get_profile_and_token(code)

    profile = profile_and_token.profile

    # The user's organization ID
    organization = "org_123"

    # Validate that this profile belongs to the organization used for authentication
    if profile.organization_id != organization:
        return "Unauthorized", 401

    # Use the information in `profile` for further business logic.

    return redirect("/")
```

```go language="go"
// workos:manual - preserve callback validation guidance
package main

import (
	"context"

	"github.com/workos/workos-go/v10"
)

func main() {
	client := workos.NewClient(
		"sk_example_123456789",
		workos.WithClientID("client_123456789"),
	)

	profileAndToken, err := client.SSO().GetProfileAndToken(context.Background(), &workos.SSOGetProfileAndTokenParams{
		Code: "authorization_code_value",
	})
	if err != nil {
		// Handle the error according to your application's needs.
		return
	}

	organizationID := "org_123"
	if profileAndToken.Profile == nil ||
		profileAndToken.Profile.OrganizationID == nil ||
		*profileAndToken.Profile.OrganizationID != organizationID {
		// Return an unauthorized response.
		return
	}

	// Use the information in `profileAndToken.Profile` for further business logic.
}
```

```php language="php"
<?php

// workos:manual - preserve callback validation guidance
use WorkOS\WorkOS;

$workos = new WorkOS(
    apiKey: "sk_example_123456789",
    clientId: "client_123456789",
);

$profileAndToken = $workos
    ->sso()
    ->getProfileAndToken(code: "authorization_code_value");

$organizationId = "org_123";
if ($profileAndToken->profile->organizationId !== $organizationId) {
    throw new \RuntimeException("Unauthorized organization");
}

// Use the information in `$profileAndToken->profile` for further business logic.
```

```php language="laravel"
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use WorkOS\Laravel\Facades\WorkOS;

Route::get("/callback", function (Request $request) {
    $code = $request->input("code");
    $profileAndToken = WorkOS::sso()->getProfileAndToken($code);

    $profile = $profileAndToken->profile;

    // The user's organization ID
    $organization = "org_123";

    // Validate that this profile belongs to the organization used for authentication
    if ($profile->organizationId != $organization) {
        return Response::json(
            [
                "message" => "Unauthorized",
            ],
            401,
        );
    }

    // Use the information in `profile` for further business logic.

    return redirect("/");
});
```

```java language="java"
// workos:manual - preserve callback validation guidance
import com.workos.WorkOS;
import com.workos.models.SSOTokenResponse;

WorkOS workos =
    WorkOS.builder().apiKey("sk_example_123456789").clientId("client_123456789").build();

SSOTokenResponse profileAndToken =
    workos.getSso().getProfileAndToken("authorization_code_value");

String organizationId = "org_123";
if (!organizationId.equals(profileAndToken.getProfile().getOrganizationId())) {
  throw new SecurityException("Unauthorized organization");
}

// Use the information in `profileAndToken.getProfile()` for further business logic.
```

```cs language="dotnet"
// workos:manual - preserve callback validation guidance
using WorkOS;

var client = new WorkOSClient(new WorkOSOptions {
    ApiKey = "sk_example_123456789",
    ClientId = "client_123456789",
});

var profileAndToken = await client.SSO.GetProfileAndTokenAsync(new SSOGetProfileAndTokenOptions {
    Code = "authorization_code_value",
});

var organizationId = "org_123";
if (profileAndToken.Profile.OrganizationId != organizationId)
{
    throw new UnauthorizedAccessException("Unauthorized organization");
}

// Use the information in `profileAndToken.Profile` for further business logic.
```

```elixir language="elixir"
# workos:manual - preserve callback validation guidance
client =
  WorkOS.client(
    api_key: "sk_example_123456789",
    client_id: "client_123456789"
  )

{:ok, profile_and_token} =
  WorkOS.SSO.get_profile_and_token(client, %{
    code: "authorization_code_value"
  })

organization_id = "org_123"

if profile_and_token.profile.organization_id != organization_id do
  raise "Unauthorized organization"
end

# Use profile_and_token.profile for further business logic.
```

```rust language="rust"
// workos:manual - preserve callback validation guidance
use workos::sso::GetProfileAndTokenParams;
use workos::{Client, TokenQuery};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::builder()
        .api_key("sk_example_123456789")
        .client_id("client_123456789")
        .build();

    let profile_and_token = client
        .sso()
        .get_profile_and_token(GetProfileAndTokenParams::new(
            "authorization_code_value",
            TokenQuery {
                client_id: "client_123456789".into(),
                client_secret: "sk_example_123456789".into(),
                code: "authorization_code_value".into(),
                grant_type: "authorization_code".into(),
            },
        ))
        .await?;

    let organization_id = "org_123";
    if profile_and_token.profile.organization_id.as_deref() != Some(organization_id) {
        return Err(std::io::Error::other("Unauthorized organization").into());
    }

    // Use the information in `profile_and_token.profile` for further business logic.

    Ok(())
}
```

:::

### Create a Passwordless Session and email the user

Create a Passwordless Session to generate an authentication link for a user. An authentication link is valid for 15 minutes and can be sent via the WorkOS API or using your own email service.

You can use the optional `state` parameter to encode arbitrary information to help restore application state between redirects.

You can use the optional `redirect_uri` parameter to override the default [Redirect URI](https://workos.com/docs/glossary/redirect-uri) set in the dashboard.

> A Magic Link Connection will be automatically created if there isn't already one for the domain specified when creating a new Passwordless Session.

- | WorkOS email

  Use the WorkOS API to send the authentication link to the user. The email sent will be WorkOS branded.

  :::code-group{title="Create a Passwordless Session"}

  ```ts language="js" title="Next.js" tab="js-1"
  import type { NextApiRequest, NextApiResponse } from 'next';
  import { WorkOS } from '@workos-inc/node';

  const workos = new WorkOS(process.env.WORKOS_API_KEY);

  export default async (req: NextApiRequest, res: NextApiResponse) => {
    if (req.method === 'POST') {
      // Email of the user to authenticate
      const email = 'email@example.com';

      const session = await workos.passwordless.createSession({
        email,
        type: 'MagicLink',
      });

      // Send an email to the user via WorkOS with the link to authenticate
      await workos.passwordless.sendSession(session.id);

      // Finally, redirect to a "Check your email" page
      res.redirect(307, '/check-email');
    }
  };
  ```

  ```js language="js" title="Express" tab="js-2"
  const express = require('express');
  const { WorkOS } = require('@workos-inc/node');

  const app = express();

  const workos = new WorkOS(process.env.WORKOS_API_KEY);

  app.post('/passwordless-auth', async (req, res) => {
    // Email of the user to authenticate
    const email = 'email@example.com';

    const session = await workos.passwordless.createSession({
      email,
      type: 'MagicLink',
    });

    // Send an email to the user via WorkOS with the link to authenticate
    await workos.passwordless.sendSession(session.id);

    // Finally, redirect to a "Check your email" page
  });
  ```

  ```rb language="ruby" title="Rails" tab="ruby-3"
  require "workos"

  WORKOS = WorkOS::Client.new(api_key: ENV["WORKOS_API_KEY"])

  def passwordless_auth
    # Email of the user to authenticate
    email = "email@example.com"

    session = WORKOS.passwordless.create_session(
      email: email,
      type: "MagicLink"
    )

    # Send an email to the user via WorkOS with the link to authenticate
    WORKOS.passwordless.send_session(session.id)

    # Finally, redirect to a "Check your email" page
  end
  ```

  ```rb language="ruby" title="Sinatra" tab="ruby-4"
  require "sinatra"
  require "workos"

  workos = WorkOS::Client.new(api_key: ENV["WORKOS_API_KEY"])

  post "/passwordless-auth" do
    # Email of the user to authenticate
    email = "email@example.com"

    session = workos.passwordless.create_session(
      email: email,
      type: "MagicLink"
    )

    # Send an email to the user via WorkOS with the link to authenticate
    workos.passwordless.send_session(session.id)

    # Finally, redirect to a "Check your email" page
  end
  ```

  ```py language="python" title="Django" tab="python-5"
  from workos import WorkOSClient

  workos_client = WorkOSClient(
      api_key="sk_example_123456789", client_id="client_123456789"
  )


  def passwordless_auth(request):
      email = request.POST["email"]  # Email of the user to authenticate

      session = workos_client.passwordless.create_session(email=email, type="MagicLink")

      # Send an email to the user via WorkOS with the link to authenticate
      workos_client.passwordless.send_session(session_id=session.id)

      # Finally, redirect to a "Check your email" page
  ```

  ```py language="python" title="Flask" tab="python-6"
  from flask import Flask, request
  from workos import WorkOSClient

  workos_client = WorkOSClient(
      api_key="sk_example_123456789", client_id="client_123456789"
  )

  app = Flask(__name__)


  @app.route("/passwordless-auth", methods=["POST"])
  def passwordless_auth():
      email = request.form["email"]  # Email of the user to authenticate

      session = workos_client.passwordless.create_session(email=email, type="MagicLink")

      # Send an email to the user via WorkOS with the link to authenticate
      workos_client.passwordless.send_session(session_id=session.id)

      # Finally, redirect to a "Check your email" page
  ```

  ```go language="go"
  package main

  import (
  	workos "github.com/workos/workos-go/v10"
  	"net/http"
  	"os"
  )

  func main() {
  	apiKey := os.Getenv("WORKOS_API_KEY")

  	client := workos.NewClient(apiKey)

  	http.HandleFunc("/passwordless-auth", func(w http.ResponseWriter, r *http.Request) {
  		r.ParseForm()

  		// Email of the user to authenticate
  		email := r.Form["email"][0]

  		session, err := client.Passwordless().CreateSession(r.Context(), &workos.PasswordlessCreateSessionParams{
  			Email: email,
  			Type:  workos.PasswordlessSessionTypeMagicLink,
  		})

  		if err != nil {
  			// Handle the error...
  		}

  		// Send an email to the user via WorkOS with the link to authenticate
  		err = client.Passwordless().SendSession(r.Context(), session.ID)

  		if err != nil {
  			// Handle the error...
  		}

  		// Finally, redirect to a "Check your email" page
  	})
  }
  ```

  ```php language="php"
  <?php

  require __DIR__ . "/vendor/autoload.php";

  $workos = new \WorkOS\WorkOS();

  switch (strtok($_SERVER["REQUEST_URI"], "?")) {
      case "/passwordless-auth":
          // Email of the user to authenticate
          $email = $_POST["email"];

          // Generate a session for passwordless
          $session = $workos
              ->passwordless()
              ->createSession(email: $email, type: "MagicLink");

          // Send an email to the user via WorkOS with the link to authenticate
          $workos->passwordless()->sendSession($session->id);

      // Finally, redirect to a "Check your email" page
  }
  ```

  ```php language="laravel"
  <?php

  use Illuminate\Http\Request;
  use Illuminate\Support\Facades\Route;
  use WorkOS\Laravel\Facades\WorkOS;

  Route::get("/auth", function (Request $request) {
      // Email of the user to authenticate
      $email = $request->input("email");

      // Generate a session for passwordless
      $session = WorkOS::passwordless()->createSession(
          email: $email,
          type: "MagicLink",
      );

      // Send an email to the user via WorkOS with the link to authenticate
      WorkOS::passwordless()->sendSession($session->id);

      // Finally, redirect to a "Check your email" page
  });
  ```

  ```java language="java"
  import com.workos.WorkOS;
  import com.workos.passwordless.PasswordlessApi.CreateSessionOptions;
  import com.workos.passwordless.models.PasswordlessSession;
  import io.javalin.Javalin;
  import java.util.Map;

  public class Application {
    public static void main(String[] args) {
      Map<String, String> env = System.getenv();
      Javalin app = Javalin.create().start(7001);
      WorkOS workos = new WorkOS(env.get("WORKOS_API_KEY"));
      String clientId = env.get("WORKOS_CLIENT_ID");

      app.get("/passwordless-auth", ctx -> {
        // Email of the user to authenticate
        String email = ctx.formParam("email");

        CreateSessionOptions options = CreateSessionOptions.builder().email(email).build();
        PasswordlessSession session = workos.passwordless.createSession(options);

        // Send an email to the user via WorkOS with the link to authenticate
        workos.passwordless.sendSession(session.id);

        // Finally, redirect to a "Check your email" page
        ctx.redirect("/check-email");
      });
    }
  }
  ```

  ```cs language="dotnet"
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Mvc;
  using WorkOS;

  namespace MyApplication.Controllers
  {
      public class PasswordlessAuthController : Controller
      {
          [HttpPost("passwordless-auth")]
          public async Task<IActionResult> Index()
          {
              var passwordlessService = new PasswordlessService();

              // Email of the user to authenticate
              string email = "email@example.com";

              var options = new CreatePasswordlessSessionOptions {
                  Email = email,
                  Type = "MagicLink",
              };

              var session = await passwordlessService.CreateSession(options);

              // Send an email to the user via WorkOS with the link to authenticate
              await passwordlessService.SendSession(session.Id);

              // Replace this path with your application's "Check your email" page
              return Redirect("/check-email");
          }
      }
  }
  ```

  ```elixir language="elixir"
  client =
    WorkOS.client(
      api_key: "sk_example_123456789",
      client_id: "client_123456789"
    )

  # Email of the user to authenticate.
  email = "marcelina@foo-corp.com"

  {:ok, session} =
    WorkOS.Passwordless.create_session(client, %{
      email: email,
      type: "MagicLink"
    })

  # Send the authentication link with WorkOS.
  {:ok, _response} = WorkOS.Passwordless.send_session(client, session.id)

  # Finally, redirect to a "Check your email" page.
  ```

  ```rust language="rust"
  use workos::{Client, PasswordlessCreateSessionParams, PasswordlessSessionType};

  #[tokio::main]
  async fn main() -> Result<(), workos::Error> {
      let client = Client::builder()
          .api_key("sk_example_123456789")
          .client_id("client_123456789")
          .build();

      // Email of the user to authenticate.
      let email = "marcelina@foo-corp.com";

      let session = client
          .passwordless()
          .create_session(PasswordlessCreateSessionParams {
              email: email.into(),
              kind: PasswordlessSessionType::MagicLink,
              redirect_uri: None,
              state: None,
              expires_in: None,
          })
          .await?;

      // Send the authentication link with WorkOS.
      client.passwordless().send_session(&session.id).await?;

      // Finally, redirect to a "Check your email" page.
      Ok(())
  }
  ```

  :::

- | Custom email

  Use your own email service and custom branded email template to send the authentication link to the user.

  :::code-group{title="Create a Passwordless Session"}

  ```ts language="js" title="Next.js" tab="js-1"
  import type { NextApiRequest, NextApiResponse } from 'next';
  import { WorkOS } from '@workos-inc/node';

  const workos = new WorkOS(process.env.WORKOS_API_KEY);

  export default async (req: NextApiRequest, res: NextApiResponse) => {
    if (req.method === 'POST') {
      // Email of the user to authenticate
      const email = 'email@example.com';

      const session = await workos.passwordless.createSession({
        email,
        type: 'MagicLink',
      });

      // Send a custom email using your own service
      emailService.send({
        email,
        message: session.link,
      });

      // Finally, redirect to a "Check your email" page
      res.redirect(307, '/check-email');
    }
  };
  ```

  ```js language="js" title="Express" tab="js-2"
  const express = require('express');
  const { WorkOS } = require('@workos-inc/node');

  const app = express();
  const workos = new WorkOS(process.env.WORKOS_API_KEY);

  app.post('/passwordless-auth', async (req, res) => {
    // Email of the user to authenticate
    const email = 'email@example.com';

    const session = await workos.passwordless.createSession({
      email,
      type: 'MagicLink',
    });

    // Send a custom email using your own service
    emailService.send({
      email,
      message: session.link,
    });

    // Finally, redirect to a "Check your email" page
  });
  ```

  ```rb language="ruby" title="Rails" tab="ruby-3"
  require "workos"

  WORKOS = WorkOS::Client.new(api_key: ENV["WORKOS_API_KEY"])

  def passwordless_auth
    # Email of the user to authenticate
    email = "email@example.com"

    session = WORKOS.passwordless.create_session(
      email: email,
      type: "MagicLink"
    )

    # Send a custom email using your own service
    EmailService.send(
      email: email,
      message: session.link
    )

    # Finally, redirect to a "Check your email" page
  end
  ```

  ```rb language="ruby" title="Sinatra" tab="ruby-4"
  require "sinatra"
  require "workos"

  workos = WorkOS::Client.new(api_key: ENV["WORKOS_API_KEY"])

  post "/passwordless-auth" do
    # Email of the user to authenticate
    email = "email@example.com"

    session = workos.passwordless.create_session(
      email: email,
      type: "MagicLink"
    )

    # Send a custom email using your own service
    EmailService.send(
      email: email,
      message: session.link
    )

    # Finally, redirect to a "Check your email" page
  end
  ```

  ```py language="python" title="Django" tab="python-5"
  from workos import WorkOSClient
  import smtplib

  workos_client = WorkOSClient(
      api_key="sk_example_123456789", client_id="client_123456789"
  )


  def passwordless_auth(request):
      email = request.POST["email"]  # Email of the user to authenticate

      session = workos_client.passwordless.create_session(email=email, type="MagicLink")

      # Send a custom email using your own service
      smtp_server = smtplib.SMTP("smtp.email.com", 587)
      smtp_server.send(email=email, message=session["link"])

      # Finally, redirect to a "Check your email" page
  ```

  ```py language="python" title="Flask" tab="python-6"
  from flask import Flask, request
  from workos import WorkOSClient
  import smtplib

  workos_client = WorkOSClient(
      api_key="sk_example_123456789", client_id="client_123456789"
  )

  app = Flask(__name__)


  @app.route("/passwordless-auth", methods=["POST"])
  def passwordless_auth():
      email = request.form["email"]  # Email of the user to authenticate

      session = workos_client.passwordless.create_session(email=email, type="MagicLink")

      # Send a custom email using your own service
      smtp_server = smtplib.SMTP("smtp.email.com", 587)
      smtp_server.send(email=email, message=session["link"])

      # Finally, redirect to a "Check your email" page
  ```

  ```go language="go"
  package main

  import (
  	workos "github.com/workos/workos-go/v10"
  	"net/http"
  	"os"
  )

  func main() {
  	apiKey := os.Getenv("WORKOS_API_KEY")

  	client := workos.NewClient(apiKey)

  	http.HandleFunc("/passwordless-auth", func(w http.ResponseWriter, r *http.Request) {
  		r.ParseForm()

  		// Email of the user to authenticate
  		userEmail := r.Form["email"][0]

  		session, err := client.Passwordless().CreateSession(r.Context(), &workos.PasswordlessCreateSessionParams{
  			Email: userEmail,
  			Type:  workos.PasswordlessSessionTypeMagicLink,
  		})

  		if err != nil {
  			// Handle the error...
  		}

  		// Send a custom email using your own service
  		sendCustomEmail(userEmail, session.Link)

  		// Finally, redirect to a "Check your email" page
  	})
  }

  func sendCustomEmail(email string, message string) {
  	// Send a custom email using your own service.
  }
  ```

  ```php language="php"
  <?php

  require __DIR__ . "/vendor/autoload.php";

  $workos = new \WorkOS\WorkOS();

  switch (strtok($_SERVER["REQUEST_URI"], "?")) {
      case "/passwordless-auth":
          // Email of the user to authenticate
          $email = $_POST["email"];

          // Generate a session for passwordless
          $session = $workos
              ->passwordless()
              ->createSession(email: $email, type: "MagicLink");

          // Send a custom email using your own service
          send($email, $session->link);

      // Finally, redirect to a "Check your email" page
  }
  ```

  ```php language="laravel"
  <?php

  use Illuminate\Http\Request;
  use Illuminate\Support\Facades\Route;
  use WorkOS\Laravel\Facades\WorkOS;

  Route::get("/auth", function (Request $request) {
      // Email of the user to authenticate
      $email = $request->input("email");

      // Generate a session for passwordless
      $session = WorkOS::passwordless()->createSession(
          email: $email,
          type: "MagicLink",
      );

      // Send a custom email using your own service
      send($email, $session->link);

      // Finally, redirect to a "Check your email" page
  });
  ```

  ```java language="java"
  import com.workos.WorkOS;
  import com.workos.passwordless.PasswordlessApi.CreateSessionOptions;
  import com.workos.passwordless.models.PasswordlessSession;
  import io.javalin.Javalin;
  import java.util.Map;

  public class Application {
    public static void main(String[] args) {
      Map<String, String> env = System.getenv();
      Javalin app = Javalin.create().start(7001);
      WorkOS workos = new WorkOS(env.get("WORKOS_API_KEY"));
      String clientId = env.get("WORKOS_CLIENT_ID");

      app.get("/passwordless-auth", ctx -> {
        // Email of the user to authenticate
        String email = ctx.formParam("email");

        CreateSessionOptions options = CreateSessionOptions.builder().email(email).build();
        PasswordlessSession session = workos.passwordless.createSession(options);

        // Send a custom email using your own service
        sendCustomEmail(email, session.link);

        // Finally, redirect to a "Check your email" page
        ctx.redirect("/check-email");
      });
    }
  }
  ```

  ```cs language="dotnet"
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Mvc;
  using WorkOS;

  namespace MyApplication.Controllers
  {
      public class PasswordlessAuthController : Controller
      {
          [HttpPost("passwordless-auth")]
          public async Task<IActionResult> Index()
          {
              var passwordlessService = new PasswordlessService();

              // Email of the user to authenticate
              string email = "email@example.com";

              var options = new CreatePasswordlessSessionOptions {
                  Email = email,
                  Type = "MagicLink",
              };

              var session = await passwordlessService.CreateSession(options);

              // SendEmailOptions and emailService are supplied by your application
              var emailOptions = new SendEmailOptions {
                  Email = email,
                  Message = session.Link,
              };

              await this.emailService.SendSession(emailOptions);

              // Replace this path with your application's "Check your email" page
              return Redirect("/check-email");
          }
      }
  }
  ```

  ```elixir language="elixir"
  client =
    WorkOS.client(
      api_key: "sk_example_123456789",
      client_id: "client_123456789"
    )

  # Email of the user to authenticate.
  email = "marcelina@foo-corp.com"

  {:ok, session} =
    WorkOS.Passwordless.create_session(client, %{
      email: email,
      type: "MagicLink"
    })

  # Send this link to email with your own email provider.
  session.link

  # Finally, redirect to a "Check your email" page.
  ```

  ```rust language="rust"
  use workos::{Client, PasswordlessCreateSessionParams, PasswordlessSessionType};

  #[tokio::main]
  async fn main() -> Result<(), workos::Error> {
      let client = Client::builder()
          .api_key("sk_example_123456789")
          .client_id("client_123456789")
          .build();

      // Email of the user to authenticate.
      let email = "marcelina@foo-corp.com";

      let session = client
          .passwordless()
          .create_session(PasswordlessCreateSessionParams {
              email: email.into(),
              kind: PasswordlessSessionType::MagicLink,
              redirect_uri: None,
              state: None,
              expires_in: None,
          })
          .await?;

      // Send this link to the email address with your own email provider.
      let _magic_link = session.link;

      // Finally, redirect to a "Check your email" page.
      Ok(())
  }
  ```

  :::

***

## (2) Configure a redirect URI

You should set a redirect URI (i.e. the callback endpoint from [Add a callback endpoint](https://workos.com/docs/magic-link/1-add-magic-link-to-your-app/add-a-callback-endpoint)) in the [Applications](https://dashboard.workos.com/environment/applications) section of the WorkOS Dashboard. Open your application and go to the **Redirects** tab – be sure not to include wildcard subdomains or query parameters.

![A screenshot showing where to add a callback in the WorkOS Dashboard.](https://images.workoscdn.com/images/43ffd916-890b-4f1f-8767-0b70113288d9.png?auto=format\&fit=clip\&q=50)
