Passwordless Authentication grant_type error when trying to verify email otp

I amtrying to implement passwordless authentication with email+otp method below is the code for signup and for request otp and verify otp and error response.

Signup

const express = require("express");
const router = express.Router();
const dotenv = require("dotenv");
const { ManagementClient } = require("auth0");
const axios = require("axios");

dotenv.config();

// Request data to obtain the access token
const requestData = {
  grant_type: "client_credentials",
  client_id: clientId,
  client_secret: clientSecret,
  audience: audience,
};

const getToken = async () => {
  try {
    const response = await axios.post(tokenUrl, requestData);
    const accessToken = response.data;
    return accessToken;
  } catch (error) {
    console.error("Error obtaining access token:", error.message);
    throw error;
  }
};

router.post("/signup", async (req, res) => {
  const { email, password, username } = req.body;

  try {
    // Obtain the access token
    const accessToken = await getToken();

    console.log(accessToken);

    // Auth0 Management API configuration
    const management = new ManagementClient({
      domain,
      clientId,
      clientSecret,
      token: accessToken
    });

    // Create a new user using the Management API
    const newUser = await management.createUser({
      email,
      password,
      username,
      connection: "Username-Password-Authentication",
      app_metadata: {
        app_name: "anasuria",
      },
    });

    // Extract the user ID from the createdUser response
    const userId = newUser.user_id;
    console.log(userId);

    res
      .status(200)
      .json({ message: "User created successfully", user: newUser });
  } catch (error) {
    console.error("Error during signup:", error.message);
    res.status(500).json({ error: error });
  }
});

module.exports = router;

Login Request Code

const express = require("express");
const router = express.Router();
const dotenv = require("dotenv");
const { AuthenticationClient, ManagementClient } = require("auth0");
const jwt = require("jsonwebtoken");
const axios = require("axios");

const auth0 = new AuthenticationClient({
  domain:  domain,
  clientId: ClienrtID,
  clientSecret: secret,
});

router.post("/magiclogin", async (req, res) => {
  const data = {
    email: req.body.email, // Replace with the user's email
    send: "code",

    authParams: {
      response_type: "token",
      scope: "openid email", // Specify the desired scope
    },
  };

  auth0.passwordless.sendEmail(data, function (err, user) {
    if (err) {
      console.error("Error sending passwordless email:", err.message);
      // Handle the error.
    } else {
      console.log(
        `Passwordless email sent successfully: ${JSON.stringify(user)}`
      );
      res.send(user);
    }
  });
});

module.exports = router;

Verify OTP

const express = require("express");
const router = express.Router();
const dotenv = require("dotenv");
const { AuthenticationClient, ManagementClient } = require("auth0");
const jwt = require("jsonwebtoken");
const axios = require("axios");

const auth0 = new AuthenticationClient({
  domain:  domain,
  clientId: ClienrtID,
  clientSecret: secret,
});
// Step 3: Magic Link for Login
router.post("/verifyotp", async (req, res) => {
  const data = {
    Grant_type: "http://auth0.com/oauth/grant-type/passwordless/otp",
    username: req.body.email,
    otp: req.body.otp,
    realm: "email", // Use "email" for OTP sent to email
    //scope: "openid profile", // Adjust the scope as needed
  };
  auth0.passwordless.signIn(data, function (err, response) {
    if (err) {
      console.error("Error verifying OTP:", err.message);
      // Handle the error.
      res.send(err);
    } else {
      console.log("OTP verified successfully.");
      res.send(response);
      // Assuming OTP verification is successful, exchange the code for an access token
    }
  });
});

module.exports = router;

Error Response

{
    "error": {
        "name": "Conflict",
        "message": "The user already exists.",
        "statusCode": 409,
        "requestInfo": {
            "method": "post",
            "url": "https://dev-e48f02pgr13we72c.us.auth0.com/api/v2/users"
        },
        "originalError": {
            "status": 409,
            "response": {
                "req": {
                    "method": "POST",
                    "url": "https://dev-e48f02pgr13we72c.us.auth0.com/api/v2/users",
                    "data": {
                        "email": "amir+3@Betalectic.com",
                        "password": "[REDACTED]",
                        "username": "amir3",
                        "connection": "Username-Password-Authentication",
                        "app_metadata": {
                            "app_name": "anasuria"
                        }
                    },
                    "headers": {
                        "content-type": "application/json",
                        "user-agent": "node.js/18.16.1",
                        "auth0-client": "eyJuYW1lIjoibm9kZS1hdXRoMCIsInZlcnNpb24iOiIzLjYuMCIsImVudiI6eyJub2RlIjoiMTguMTYuMSJ9fQ",
                        "authorization": "[REDACTED]",
                        "accept": "application/json"
                    }
                },
                "header": {
                    "date": "Wed, 09 Aug 2023 03:39:22 GMT",
                    "content-type": "application/json; charset=utf-8",
                    "content-length": "104",
                    "connection": "close",
                    "cf-ray": "7f3cf8b7ea089a9f-NAG",
                    "cf-cache-status": "DYNAMIC",
                    "cache-control": "no-cache",
                    "strict-transport-security": "max-age=31536000",
                    "vary": "origin, Accept-Encoding",
                    "access-control-expose-headers": "WWW-Authenticate,Server-Authorization",
                    "ot-baggage-auth0-request-id": "7f3cf8b7ea089a9f",
                    "ot-tracer-sampled": "true",
                    "ot-tracer-spanid": "794d10fe3e9c5153",
                    "ot-tracer-traceid": "161fb0d811ccd2e3",
                    "traceparent": "00-0000000000000000161fb0d811ccd2e3-794d10fe3e9c5153-01",
                    "tracestate": "auth0-request-id=7f3cf8b7ea089a9f,auth0=true",
                    "x-content-type-options": "nosniff",
                    "server": "cloudflare",
                    "alt-svc": "h3=\":443\"; ma=86400"
                },
                "status": 409,
                "text": "{\"statusCode\":409,\"error\":\"Conflict\",\"message\":\"The user already exists.\",\"errorCode\":\"auth0_idp_error\"}"
            }
        }
    }
}
1 Like

Hi @AMIR1998,

That error indicates that the user you are trying to create (it looks like in your Signup code) already exists.

Do you still see this error if you send a new user with the request?

@dan.woda
I encountered issues when attempting to set up a new user. Therefore, I’ve reconsidered my approach and opted for the Management API instead. The passwordless login method seemed to introduce quite a bit of confusion, involving code transmission to mobile devices or email, followed by code verification or the dispatch of a magic login link. Unfortunately, the documentation didn’t comprehensively explain these concepts, and I also noticed a lack of tutorials on Auth0’s YouTube channel that could have simplified the process.

Given this situation, I’ve transitioned to utilizing the Management API and have decided to forgo the passwordless login approach. Thank you for your assistance.

1 Like

No problem, thanks for the thorough update. I’ll mark this resolved without a solution.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.