> ## Documentation Index
> Fetch the complete documentation index at: https://auth0-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> A widget that provides a frictionless login and signup experience for your web apps.

# Lock for Web

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Lock is an embeddable login form that can be [configured to your needs](/docs/libraries/lock/lock-configuration). Lock enables you to easily add social <Tooltip tip="Identity Provider (IdP): Service that stores and manages digital identities." cta="View Glossary" href="/docs/glossary?term=identity+providers">identity providers</Tooltip>, so that your users can log in seamlessly using any desired provider.

<Warning>
  Embedded login for web applications uses [cross-origin authentication](/docs/authenticate/login/cross-origin-authentication) unless you [configure a custom domain](/docs/customize/custom-domains) for your tenant. Cross-origin authentication uses third-party cookies to allow for secure authentication transactions across different origins.
</Warning>

## Lock Installation

You can install Lock via several methods. Select any of the following installation sources that best suit your environment and application.

### Installation Sources

Install via [npm](https://npmjs.org):
`npm install auth0-lock`

Install via [bower](http://bower.io):

`bower install auth0-lock`

Include via our CDN (Replace `.x` and `.y` with the latest minor and patch release numbers from the [Lock Github repository](https://github.com/auth0/lock/releases):

Latest Minor Release:`<script src="https://cdn.auth0.com/js/lock/11.x/lock.min.js"></script>`Latest Patch Release:
`<script src="https://cdn.auth0.com/js/lock/11.x.y/lock.min.js"></script>`

It is recommended that production applications use a specific patch version, or at the very least a specific minor version. Regardless of the method by which Lock is included, the recommendation is that the version should be locked down and only manually updated, to ensure that those updates do not adversely affect your implementation. Check the [GitHub repository](https://github.com/auth0/lock/releases) for a current list of releases.

### Mobile

If you are targeting mobile audiences, Auth0 recommends that you add the following meta tag to your application's `head`:

`<meta name="viewport" content="width=device-width, initial-scale=1"/>`

### Bundling Dependencies

If you are using browserify or webpack to build your project and bundle its dependencies, after installing the `auth0-lock` module, you will need to bundle it with all its dependencies. Examples are available for [Browserify](https://github.com/auth0/lock/tree/master/examples/bundling/browserify) and [webpack](https://github.com/auth0/lock/tree/master/examples/bundling/webpack).

### Cross-Origin Authentication

<Warning>
  Embedded login for web applications uses [cross-origin authentication](/docs/authenticate/login/cross-origin-authentication) unless you [configure a custom domain](/docs/customize/custom-domains) for your tenant. Cross-origin authentication uses third-party cookies to allow for secure authentication transactions across different origins.
</Warning>

Embedding Lock within your application requires [cross-origin authentication](/docs/authenticate/login/cross-origin-authentication) to be properly configured. Specifically, you need to set the **Allowed Web Origins** property to the domain making the request. You can find this field in the [Application Settings](https://manage.auth0.com/#/applications/\{yourClientId}/settings).

## Usage

### Step 1. Initializing Lock

First, you'll need to initialize a new `Auth0Lock` object, and provide it with your Auth0 <Tooltip tip="Client ID: Identification value given to your registered resource from Auth0." cta="View Glossary" href="/docs/glossary?term=client+ID">client ID</Tooltip> (the unique client ID for each Auth0 application, which you can get from the [management dashboard](https://manage.auth0.com/#)) and your Auth0 domain (for example `yourname.auth0.com`).

export const codeExample1 = `// Initializing our Auth0Lock
var lock = new Auth0Lock(
  '{yourClientId}',
  '{yourDomain}'
);`;

<AuthCodeBlock children={codeExample1} language="js" />

### Step 2. Authenticating and Getting User Info

Next, listen using the `on` method for the `authenticated` event. When the event occurs, use the `accessToken` which was received to call the `getUserInfo` method and acquire the user's profile information (as needed).

export const codeExample2 = `var Auth = (function() {

  var wm = new WeakMap();
  var privateStore = {};
  var lock;

  function Auth() {
    this.lock = new Auth0Lock(
      '<{yourClientId}>',
      '<{yourDomain}>'
    );
    wm.set(privateStore, {
      appName: "example"
    });
  }

  Auth.prototype.getProfile = function() {
    return wm.get(privateStore).profile;
  };

  Auth.prototype.authn = function() {
    // Listening for the authenticated event
    this.lock.on("authenticated", function(authResult) {
      // Use the token in authResult to getUserInfo() and save it if necessary
      this.getUserInfo(authResult.accessToken, function(error, profile) {
        if (error) {
          // Handle error
          return;
        }

        //we recommend not storing Access Tokens unless absolutely necessary
        wm.set(privateStore, {
          accessToken: authResult.accessToken
        });

        wm.set(privateStore, {
          profile: profile
        });

      });
    });
  };
  return Auth;
}());`;

<AuthCodeBlock children={codeExample2} language="js" />

You can then manipulate page content and display profile information to the user (for example, displaying their name in a welcome message).

`<h2>Welcome <span id="nick" class="nickname"></span></h2>`

Note that if you are storing the user profile, you will want to `JSON.stringify` the profile object and then, when using it later, `JSON.parse` it, because it will need to be stored in `localStorage` as a string rather than a JSON object.

### Step 3. Showing Lock

Here you're showing the Lock widget after the user clicks a login button; you can just as easily show Lock automatically when arriving at a page by just using `lock.show();` on page load.

This will show the Lock widget, and paired with the above, you're now ready to handle logins!

```js lines theme={null}
document.getElementById('btn-login').addEventListener('click', function() {
  lock.show();
});
```

## Passwordless

Lock's <Tooltip tip="Passwordless: Form of authentication that does not rely on a password as the first factor." cta="View Glossary" href="/docs/glossary?term=Passwordless">Passwordless</Tooltip> Mode is only available in Lock v11.2.0 and later. Please use the [latest release of Lock](https://github.com/auth0/lock/releases) for this feature!

You can use Lock's Passwordless Mode to allow users to authenticate using just an email or mobile number. They will receive the code and then return to input it, or click the link, and they can be authenticated without remembering a password.

In Lock, in order to implement Passwordless Mode, you initialize Lock in a slightly different manner, with `Auth0LockPasswordless` rather than with `Auth0Lock`:

export const codeExample3 = `var lockPasswordless = new Auth0LockPasswordless(
 '{yourClientId}',
 '{yourDomain}'
);`;

<AuthCodeBlock children={codeExample3} language="js" />

### Passwordless options

Additionally, Lock's Passwordless Mode has a couple of configuration options that are unique to it.

In order to indicate which connection type you would like, you initialize Lock with the `allowedConnections` option with either `email` or `sms` as the value:

```js lines theme={null}
var passwordlessOptions = {
  allowedConnections: ['sms']
}
```

Remember to enable the passwordless connection of your choice in the [Dashboard](https://manage.auth0.com/#) under **Connections -> Passwordless**, and then to enable it for your application, that way when Lock tries to use it, it is already set up and linked to the application.

If you choose to use `email`, you have one more option to select - whether you wish your users to receive a code to input, or a "magic link" to use. This is done via the `passwordlessMethod` option, which takes values of `code` or `link`.

```js lines theme={null}
var passwordlessOptions = {
  allowedConnections: ['email'],
  passwordlessMethod: 'code'
}
```

### Passwordless example

export const codeExample4 = `var passwordlessOptions = {
  allowedConnections: ['email'],
  passwordlessMethod: 'code',
  auth: {
    redirectUrl: 'http://localhost:3000/callback',   
    responseType: 'token id_token',
    params: {
      scope: 'openid email'               
    }          
  }
}

var lockPasswordless = new Auth0LockPasswordless(
 '{yourClientId}',
 '{yourDomain}',
 passwordlessOptions
);`;

<AuthCodeBlock children={codeExample4} language="js" />

### Single Sign-On with embedded authentication

Embedded login supports <Tooltip tip="Single Sign-On (SSO): Service that, after a user logs into one applicaton, automatically logs that user in to other applications." cta="View Glossary" href="/docs/glossary?term=Single+Sign-on">Single Sign-on</Tooltip> (SSO) when your applications share the following architecture:

* The applications attempting SSO are first-party applications. Sharing embedded sessions with third-party applications is not supported.
* The applications and your Auth0 tenant share a top-level domain via a [custom domain](/docs/customize/custom-domains). By default, Auth0 domains use the `example.auth0.com` format. Custom domains let your applications and Auth0 tenant share the same top-level domain, which also helps prevent CSRF attacks.

When your architecture meets these criteria, embedded SSO with Lock is a good fit. <Tooltip tip="Universal Login: Your application redirects to Universal Login, hosted on Auth0's Authorization Server, to verify a user's identity." cta="View Glossary" href="/docs/glossary?term=Universal+Login">Universal Login</Tooltip> handles SSO across multiple domains or with [third-party applications](/docs/get-started/applications/third-party-applications/configure-third-party-applications) automatically through its session layer. The two can coexist in the same app (for example, Universal Login for primary sign-in and Lock for embedded factor enrollment or step-up flows). To compare the trade-offs, read [Hosted Login vs. Embedded Login](/docs/authenticate/login/universal-vs-embedded-login).

## Error Codes and Descriptions

When Lock is used for embedded login, it employs the `/co/authenticate` endpoint, which has the following errors.

The error description is human readable. It **should not be parsed by any code** and it subject to change at any time.

| **Status** | **Code**                      | **Description**                                                                                                                                                                  |
| ---------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 400        | invalid\_request              | Invalid request body. All and only of client\_id, credential\_type, username, otp, realm are required.                                                                           |
| 401        | unauthorized\_client          | Cross origin login not allowed.                                                                                                                                                  |
| 400        | unsupported\_credential\_type | Unknown credential type parameter.                                                                                                                                               |
| 400        | invalid\_request              | Unknown realm non-existent-connection.                                                                                                                                           |
| 403        | access\_denied                | Wrong email or password.                                                                                                                                                         |
| 403        | access\_denied                | Authentication error                                                                                                                                                             |
| 403        | blocked\_user                 | Blocked user                                                                                                                                                                     |
| 401        | password\_leaked              | This login attempt has been blocked because the password you're using was previously disclosed through a data breach (not in this application).                                  |
| 429        | too\_many\_attempts           | Your account has been blocked after multiple consecutive login attempts. We've sent you a notification via your preferred contact method with instructions on how to unblock it. |
| 429        | too\_many\_attempts           | We have detected suspicious login behavior and further attempts will be blocked. Please contact the administrator.                                                               |

## Browser Compatibility

Browser compatibility is ensured for **Chrome**, **Safari**, **Firefox** and **IE >= 10**. Auth0 currently uses [zuul](https://github.com/defunctzombie/zuul) along with [Saucelabs](https://saucelabs.com) to run integration tests on each push.

## Learn more

* [Lock API Reference](/docs/libraries/lock/lock-api-reference)
* [Lock Configuration Options](/docs/libraries/lock/lock-configuration)
