UNPKG

27.1 kBMarkdownView Raw
1[![NPM version][npm-image]][npm-url]
2[![Build status][circleci-image]][circleci-url]
3[![Dependency Status][david-image]][david-url]
4[![License][license-image]][license-url]
5[![Downloads][downloads-image]][downloads-url]
6
7# Lock
8
9[Auth0](https://auth0.com) is an authentication broker that supports both social and enterprise identity providers, including Active Directory, LDAP, Google Apps, and Salesforce.
10
11## Install
12
13From CDN
14
15```html
16<!-- Latest patch release (recommended for production) -->
17<script src="http://cdn.auth0.com/js/lock/11.2.2/lock.min.js"></script>
18```
19
20From [npm](https://npmjs.org)
21
22```sh
23npm install auth0-lock
24```
25
26After installing the `auth0-lock` module, you'll need bundle it up along with all of its dependencies. See examples for [browserify](examples/bundling/browserify/) and [webpack](examples/bundling/webpack/).
27
28> It is expected that you use the development mode when working on your app, and the production mode when deploying your app to the users.
29> You can find instructions for building your app for production with different module bundlers [here](https://reactjs.org/docs/optimizing-performance.html#use-the-production-build).
30
31If you are targeting mobile audiences, we recommended that you add:
32
33```html
34<meta name="viewport" content="width=device-width, initial-scale=1"/>
35```
36## Cross Origin Authentication
37
38Lock uses **Cross-Origin Authentication**, make sure you understand the considerations you need to take into account by reading the [Cross-Origin Authentication documentation](https://auth0.com/docs/cross-origin-authentication).
39
40## API
41
42### new Auth0Lock(clientID, domain, options)
43
44Initializes a new instance of `Auth0Lock` configured with your application `clientID` and your account's `domain` at [Auth0](https://manage.auth0.com/). You can find this information at your [application settings](https://manage.auth0.com/#/applications).
45
46- **clientId {String}**: Your application _clientId_ in Auth0.
47- **domain {String}**: Your Auth0 _domain_. Usually _your-account.auth0.com_.
48- **options {Object}**: Allows you to customize the dialog's appearance and behavior. See [below](#customization) for the details.
49
50#### Example
51
52```js
53var clientId = "YOUR_AUTH0_APP_CLIENTID";
54var domain = "YOUR_DOMAIN_AT.auth0.com";
55var lock = new Auth0Lock(clientId, domain);
56
57lock.on("authenticated", function(authResult) {
58 lock.getUserInfo(authResult.accessToken, function(error, profile) {
59 if (error) {
60 // Handle error
61 return;
62 }
63
64 localStorage.setItem("accessToken", authResult.accessToken);
65 localStorage.setItem("profile", JSON.stringify(profile));
66
67 // Update DOM
68 });
69});
70```
71
72### getUserInfo(accessToken, callback)
73
74Once the user has logged in and you are in possesion of an access token, you can obtain the profile with `getUserInfo`.
75
76- **accessToken {String}**: User access token.
77- **callback {Function}**: Will be invoked after the user profile been retrieved.
78
79#### Example
80
81```js
82lock.getUserInfo(accessToken, function(error, profile) {
83 if (!error) {
84 alert("hello " + profile.name);
85 }
86});
87```
88
89### on(event, callback)
90
91Lock will emit events during its lifecycle.
92
93- `show`: emitted when Lock is shown. Has no arguments.
94- `hide`: emitted when Lock is hidden. Has no arguments.
95- `unrecoverable_error`: emitted when there is an unrecoverable error, for instance when no connection is available. Has the error as the only argument.
96- `authenticated`: emitted after a successful authentication. Has the authentication result as the only argument.
97- `authorization_error`: emitted when authorization fails. Has error as the only argument.
98- `hash_parsed`: every time a new Auth0Lock object is initialized in redirect mode (the default), it will attempt to parse the hash part of the url looking for the result of a login attempt. This is a _low level_ event for advanced use cases and _authenticated_ and _authorization_error_ should be preferred when possible. After that this event will be emitted with `null` if it couldn't find anything in the hash. It will be emitted with the same argument as the `authenticated` event after a successful login or with the same argument as `authorization_error` if something went wrong. This event won't be emitted in popup mode because there is no need to parse the url's hash part.
99- `forgot_password ready`: emitted when the "Forgot password" screen is shown.
100- `forgot_password submit`: emitted when the user clicks on the submit button of the "Forgot password" screen.
101- `signin submit`: emitted when the user clicks on the submit button of the "Login" screen.
102- `signup submit`: emitted when the user clicks on the submit button of the "Sign up" screen.
103- `federated login`: emitted when the user clicks on a social connection button. Has the connection name and the strategy as arguments.
104
105### show(options)
106
107Displays the widget, allowing to override some options.
108
109- **options {Object}**: Allows you to customize some aspect of the dialog's appearance and behavior. The options allowed in here are subset of the options allowed in the constructor and will override them: `allowedConnections`, `auth.params`, `allowLogin`, `allowSignUp`, `allowForgotPassword`, `initialScreen`, `rememberLastLogin` and `flashMessage`. See [below](#customization) for the details. Keep in mind that `auth.params` will be fully replaced and not merged.
110
111#### Example
112
113```js
114// without options
115lock.show();
116
117// will override the allowedConnections option passed to the constructor, if any
118lock.show({allowedConnections: ["twitter", "facebook"]})
119
120// will override the entire auth.params object passed to the constructor, if any
121lock.show({auth: {params: {state: 'auth_state'}}})
122```
123
124### resumeAuth(hash, callback)
125
126If you set the [auth.autoParseHash](#authentication-options) option to `false`, you'll need to call this method to complete the authentication flow. This method is useful when you're using a client-side router that uses a `#` to handle urls (angular2 with `useHash` or react-router with `hashHistory`).
127- **hash {String}**: The hash fragment received from the redirect.
128- **callback {Function}**: Will be invoked after the parse is done. Has an error (if any) as the first argument and the authentication result as the second one. If there is no hash available, both arguments will be `null`.
129
130#### Example
131
132```js
133lock.resumeAuth(hash, function(error, authResult) {
134 if (error) {
135 alert("Could not parse hash");
136 }
137 console.log(authResult.accessToken);
138});
139```
140
141### logout(options)
142
143Logs out the user
144
145- **options {Object}**: This is optional and follows the same rules as [this](https://auth0.com/docs/libraries/auth0js#logout)
146
147#### Example
148
149```js
150lock.logout({ returnTo: 'https://myapp.com/bye-bye' });
151```
152
153### checkSession(options, callback)
154
155The checkSession method allows you to acquire a new token from Auth0 for a user who is already authenticated against the hosted login page for your domain. The method accepts any valid OAuth2 parameters that would normally be sent to authorize. In order to use this method, you have to enable Web Origins for your client. For more information, see [Using checkSession to acquire new tokens](https://auth0.com/docs/libraries/auth0js#using-checksession-to-acquire-new-tokens).
156- **options {Object}**: OAuth2 options object to send to Auth0's servers.
157- **callback {Function}**: Will be invoked after the response from the server is returned. Has an error (if any) as the first argument and the authentication result as the second one.
158
159#### Example
160
161```js
162lock.checkSession({}, function (error, authResult) {
163 if (error || !authResult) {
164 lock.show();
165 } else {
166 // user has an active session, so we can use the accessToken directly.
167 lock.getUserInfo(authResult.accessToken, function (error, profile) {
168 console.log(error, profile);
169 });
170 }
171});
172```
173
174### Customization
175
176The appearance of the widget and the mechanics of authentication can be customized with an `options` object which has one or more of the following properties. Each method that opens the dialog can take an `options` object as its first argument.
177
178#### UI options
179
180- **allowedConnections {Array}**: List of connection that will be available to perform the authentication. It defaults to all enabled connections.
181- **autoclose {Boolean}**: Determines whether or not the Lock will be closed automatically after a successful sign in. If the Lock is not `closable` it won't be closed even if this option is set to `true`. Defaults to `false`.
182- **autofocus {Boolean}**: Determines whether or not the first input on the screen, that is the email or phone number input, should have focus when the Lock is displayed. Defaults to `false` when a `container` option is provided or the Lock is being render on a mobile device. Otherwise it defaults to `true`.
183- **avatar {Object}**: Determines whether or not an avatar and a user name should be displayed on the Lock's header once an email or username has been entered and how to obtain it. By default avatars are fetched from [Gravatar](http://gravatar.com/). Supplying `null` will disable the functionality. To fetch avatar from other provider see [below](#avatar-provider).
184- **container {String}**: The `id` of the html element where the Lock will be rendered. This makes the Lock appear inline instead of in a modal window.
185- **language {String}**: Specifies the language of the widget. Defaults to `"en"`. Supported languages are:
186 - `de`: German
187 - `en`: English
188 - `es`: Spanish
189 - `it`: Italian
190 - `nb`: Norwegian bokmål
191 - `pt-BR`: Brazilian Portuguese
192 - `ru`: Russian
193 - `zh`: Chinese
194 - `ja`: Japanese
195 - [Check all the available languages](https://github.com/auth0/lock/tree/master/src/i18n)
196- **languageDictionary {Object}**: Allows you to customize every piece of text displayed in the Lock. Defaults to `{}`. See below [Language Dictionary Specification](#language-dictionary-specification) for the details.
197- **closable {Boolean}**: Determines whether or not the Lock can be closed. When a `container` option is provided its value is always `false`, otherwise it defaults to `true`.
198- **popupOptions {Object}**: Allows you to customize the location of the popup in the screen. Any [position and size feature](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Position_and_size_features) allowed by `window.open` is accepted. Defaults to `{}`.
199- **rememberLastLogin {Boolean}**: Determines whether or not to show a screen that allows you to quickly log in with the account you used the last time when the `initialScreen` option is set to to `"login"` (the default). Defaults to `true`.
200- **flashMessage {Object}**: Shows an `error` or `success` flash message when Lock is shown.
201 + **type {String}**: The message type, it should be `error` or `success`.
202 + **text {String}**: The text to show.
203- **allowAutocomplete {Boolean}**: Determines whether or not the the email or username inputs will allow autocomplete (`<input autocomplete />`). Defaults to `false`.
204- **scrollGlobalMessagesIntoView {Boolean}**: Determines whether or not a globalMessage should be scrolled into the user's viewport. Defaults to `true`.
205- **allowShowPassword {Boolean}**: Determines whether or not add a checkbox to show the password when typing it. Defaults to `false`.
206
207
208#### Theming options
209
210Theme options are grouped in the `theme` property of the `options` object.
211
212```js
213var options = {
214 theme: {
215 labeledSubmitButton: false,
216 logo: "https://example.com/assets/logo.png",
217 primaryColor: "green",
218 authButtons: {
219 connectionName: {
220 displayName: "...",
221 primaryColor: "...",
222 foregroundColor: "...",
223 icon: "http://.../logo.png"
224 }
225 }
226 }
227};
228```
229
230- **labeledSubmitButton {Boolean}**: Indicates whether or not the submit button should have a label. Defaults to `true`. When set to `false` a icon will be shown. The labels can be customized through the `languageDictionary`.
231- **logo {String}**: Url for an image that will be placed in the Lock's header. Defaults to Auth0's logo.
232- **primaryColor {String}**: Defines the primary color of the Lock, all colors used in the widget will be calculated from it. This option is useful when providing a custom `logo` to ensure all colors go well together with the logo's color palette. Defaults to `"#ea5323"`.
233- **authButtons {Object}**: Allows the customization of the custom oauth2 login buttons.
234 + **displayName {String}**: The name to show instead of the connection name.
235 + **primaryColor {String}**: The button's background color. Defaults to `"#eb5424"`.
236 + **foregroundColor {String}**: The button's text color. Defaults to `"#FFFFFF"`.
237 + **icon {String}**: The icon's url for the connection. For example:`"http://site.com/logo.png"`.
238
239#### Authentication options
240
241Authentication options are grouped in the `auth` property of the `options` object. The default scope used by Lock is `openid profile email`.
242
243```js
244var options = {
245 auth: {
246 params: {
247 param1: "value1",
248 scope: "openid profile email"
249 },
250 autoParseHash: true,
251 redirect: true,
252 redirectUrl: "some url",
253 responseMode: "form_post",
254 responseType: "token",
255 sso: true,
256 connectionScopes: {
257 connectionName: [ 'scope1', 'scope2' ]
258 }
259 }
260};
261```
262
263- **params {Object}**: Specifies extra parameters that will be sent when starting a login. Defaults to `{}`.
264- **autoParseHash {Boolean}**: When set to `true`, Lock will parse the `window.location.hash` string when instantiated. If set to `false`, you'll have to manually resume authentication using the [resumeAuth](#resumeauthhash-callback) method.
265- **redirect {Boolean}**: When set to `true`, the default, _redirect mode_ will be used. Otherwise, _popup mode_ is chosen. See [below](#popup-mode) for more details.
266- **redirectUrl {String}**: The url Auth0 will redirect back after authentication. Defaults to the empty string `""` (no redirect URL).
267- **responseMode {String}**: Should be set to `"form_post"` if you want the code or the token to be transmitted via an HTTP POST request to the `redirectUrl` instead of being included in its query or fragment parts. Otherwise, it should be ommited.
268- **responseType {String}**: Should be set to `"token"` for Single Page Applications, and `"code"` otherwise. Also, `"id_token"` is supported for the first case. Defaults to `"code"` when `redirectUrl` is provided, and to `"token"` otherwise.
269- **sso {Boolean}**: Determines whether Single Sign On is enabled or not in **Lock**. The Auth0 SSO session will be created regardless of this option if SSO is enabled for your client or tenant.
270- **connectionScopes {Object}**: Allows you to set scopes to be sent to the oauth2/social connection for authentication.
271
272#### Social options
273
274- **socialButtonStyle {String}**: Determines the size of the buttons for the social providers. Possible values are `"big"` and `"small"`. The default style depends on the connections that are available:
275 - If only social connections are available, it will default to `"big"` when there are 5 connections at most, and default to `"small"` otherwise.
276 - If connections from types other than social are also available, it will default to `"big"` when there are 3 social connections at most, and default to `"small"` otherwise.
277
278#### Database options
279
280- **additionalSignUpFields {Array}**: Allows you to provide extra input fields during sign up. See [below](#additional-sign-up-fields) more for details. Defaults to `[]`.
281- **allowLogin {Boolean}**: When set to `false` the widget won't display the _login screen_. This is useful if you want to use the widget just for sign ups (the _login and sign up tabs_ in the _sign up screen_ will be hidden) or to reset passwords (the _back button_ in the _forgot password screen_ will be hidden). In such cases you may also need to specify the `initialScreen`, `allowForgotPassword` and `allowSignUp` options. It defaults to `true`.
282- **allowForgotPassword {Boolean}**: When set to `false` hides the _"Don't remember your password?"_ link in the _login screen_, making the _forgot password screen_ unreachable. Defaults to `true`. Keep in mind that if you are using a database connection with a _custom database_ which doesn't have a _change password script_ the forgot password screen won't be available.
283- **allowSignUp {Boolean}**: When set to `false` hides the _login and sign up tabs_ in the _login screen_, making the _sign up screen_ unreachable. Defaults to `true`. Keep in mind that if the database connection has sign ups _disabled_ or you are using a _custom database_ which doesn't have a _create script_, then the sign up screen won't be available.
284- **defaultDatabaseConnection {String}**: Specifies the database connection that will be used when there is more than one available.
285- **initialScreen {String}**: Name of the screen that will be shown when the widget is opened. Valid values are `"login"`, `"signUp"`, and `"forgotPassword"`. If this option is left unspecified, the widget will pick the first screen that is available from the previous list. If you set `initialScreen` to `"forgotPassword"` we recommend that you set `allowLogin` to `"false"`, otherwise a back button will be shown in the forgot password screen and it might not be clear to the user where that back button will take them.
286- **loginAfterSignUp {Boolean}**: Determines whether or not the user will be automatically signed in after a successful sign up. Defaults to `true`.
287- **forgotPasswordLink {String}**: URL for a page that allows the user to reset her password. When set to a non-empty string, the user will be linked to the provided URL when clicking the _"Don't remember your password?"_ link in the _login screen_.
288- **mustAcceptTerms {Boolean}**: When set to `true` displays a checkbox input along with the terms and conditions that must be checked before signing up. The terms and conditions can be specified via the `languageDictionary` option, see the example below. Defaults to `false`.
289- **prefill {Object}**: Allows you to set the initial value for the _email_ and/or _username_ inputs, e.g. `{prefill: {email: "someone@auth0.com", username: "someone"}}`. When omitted no initial value will be provided.
290- **signUpLink {String}**: URL for a page that allows the user to sign up. When set to a non-empty string, the user will be linked to the provided URL when clicking the _sign up_ tab in the _login screen_.
291- **usernameStyle {String}**: Determines what will be used to identify the user for a Database connection that has the `requires_username` flag set, otherwise it will be ignored. Possible values are `"username"` and `"email"` and by default both `username` and `email` are allowed.
292
293#### Enterprise options
294
295- **defaultEnterpriseConnection {String}**: Specifies the enterprise connection which allows you to login using an username and a password that will be used when there is more than one available or there is a database connection. If a `defaultDatabaseConnection` is provided the database connection will be used and this option will be ignored.
296
297#### Example
298
299```js
300var options = {
301 container: "myContainer",
302 closable: false,
303 languageDictionary: {
304 signUpTerms: "I agree to the <a href='/terms' target='_new'>terms of service</a> and <a href='/privacy' target='_new'>privacy policy</a>.",
305 title: "My Company",
306 },
307 autofocus: false
308};
309```
310
311#### Other options
312
313- **configurationBaseUrl {String}**: Overrides client settings base url. By default it uses Auth0's CDN url when `domain` has the format `*.auth0.com`. Otherwise, it uses the provided `domain`.
314- **languageBaseUrl {String}**: Overrides the language source url for Auth0's provided translations. By default it uses to Auth0's CDN url `https://cdn.auth0.com`.
315- **hashCleanup {Boolean}**: When enabled, it will remove the hash part of the callback url after the user authentication. Defaults to `true`.
316- **connectionResolver {Function}**: When in use, provides an extensibility point to make it possible to choose which connection to use based on the username information. Has `username`, `context` and `callback` as parameters. The callback expects an object like: `{type: 'database', name: 'connection name'}`. **This only works for database connections.** Keep in mind that this resolver will run in the username/email input's `onBlur` event, so keep it simple and fast. **This is a beta feature. If you find a bug, please open a github [issue](https://github.com/auth0/lock/issues/new).**
317
318```js
319var options = {
320 connectionResolver: function (username, context, cb) {
321 var domain = username.includes('@') && username.split('@')[1];
322 if (domain) {
323 // If the username is test@auth0.com, the connection used will be the `auth0.com` connection.
324 // Make sure you have a database connection with the name `auth0.com`.
325 cb({ type: 'database', name: domain });
326 } else {
327 // Use the default approach to figure it out the connection
328 cb(null);
329 }
330 }
331}
332```
333
334#### Language Dictionary Specification
335
336A language dictionary is an object that allows you to customize every piece of text the Lock needs to display. For instance, the following code will change the title displayed in the header and the placeholder for the email field.
337
338```js
339var options = {
340 languageDictionary: {
341 emailInputPlaceholder: "please enter you email",
342 title: "My Company"
343 },
344};
345```
346
347#### Additional sign up fields
348
349Extra input fields can be added to the sign up screen with the `additionalSignUpFields` option. Every input must have a `name` and a `placeholder`, and an `icon` url can also be provided. Also, the initial value can be provided with the `prefill` option, which can be a **string** with the value or a **function** that obtains it. Other options depend on the type of the field, which is defined via the `type` option and defaults to `"text"`.
350
351Additional sign up fields are rendered below the default fields in the order they are provided.
352
353##### Text field
354
355A `validator` function can also be provided.
356
357```js
358var options = {
359 additionalSignUpFields: [{
360 name: "address",
361 placeholder: "enter your address",
362 // The following properties are optional
363 icon: "https://example.com/assests/address_icon.png",
364 prefill: "street 123",
365 validator: function(address) {
366 return {
367 valid: address.length >= 10,
368 hint: "Must have 10 or more chars" // optional
369 };
370 }
371 }]
372}
373```
374
375##### Select field
376
377To specify a select field `type: "select"` needs to be provided along with the `options` property.
378
379```js
380var options = {
381 additionalSignUpFields: [{
382 type: "select",
383 name: "location",
384 placeholder: "choose your location",
385 options: [
386 {value: "us", label: "United States"},
387 {value: "fr", label: "France"},
388 {value: "ar", label: "Argentina"}
389 ],
390 // The following properties are optional
391 icon: "https://example.com/assests/location_icon.png",
392 prefill: "us"
393 }]
394}
395```
396
397The `options` and the `prefill` value can be provided through a function.
398
399```js
400var options = {
401 additionalSignUpFields: [{
402 type: "select",
403 name: "location",
404 placeholder: "choose your location",
405 options: function(cb) {
406 // obtain options, in case of error you call cb with the error in the
407 // first arg instead of null
408 cb(null, options);
409 },
410 icon: "https://example.com/assests/location_icon.png",
411 prefill: function(cb) {
412 // obtain prefill, in case of error you call cb with the error in the
413 // first arg instead of null
414 cb(null, prefill);
415 }
416 }]
417}
418```
419
420##### Checkbox field
421
422To specify a checkbox field use: `type: "checkbox"`
423The `prefill` value can determine the default state of the checkbox and it is required.
424
425```js
426var options = {
427 additionalSignUpFields: [{
428 type: "checkbox",
429 name: "newsletter",
430 prefill: "true",
431 placeholder: "I hereby agree that I want to receive marketing emails from your company",
432 }]
433}
434```
435
436#### Avatar provider
437
438Lock can show avatars fetched from anywhere. A custom avatar provider can be specified with the `avatar` option by passing an object with the keys `url` and `displayName`. Both properties are functions that take an email and a callback function.
439
440```js
441var options = {
442 avatar: {
443 url: function(email, cb) {
444 // obtain url for email, in case of error you call cb with the error in
445 // the first arg instead of null
446 cb(null, url);
447 },
448 displayName: function(email, cb) {
449 // obtain displayName for email, in case of error you call cb with the
450 // error in the first arg instead of null
451 cb(null, displayName);
452 }
453 }
454};
455```
456
457### Popup mode
458
459A popup window can be displayed instead of redirecting the user to a social provider website. While this has the advantage of preserving page state, it has some issues. Often times users have popup blockers that prevent the login page from even displaying. There are also known issues with mobile browsers. For example, in recent versions of Chrome on iOS, the login popup does not [close properly](https://github.com/auth0/lock/issues/71) after login. For these reasons, we encourage developers to avoid this mode, even with Single Page Apps.
460
461If you decide to use popup mode you can activate it by passing the option `auth: {redirect: false}` when constructing `Auth0Lock`.
462
463```js
464var clientId = "YOUR_AUTH0_APP_CLIENTID";
465var domain = "YOUR_DOMAIN_AT.auth0.com";
466var options = {
467 auth: {
468 redirect: false
469 }
470};
471
472var lock = new Auth0Lock(clientId, domain, options);
473lock.show();
474```
475
476More information can be found in [Auth0's documentation](https://auth0.com/docs/libraries/lock/popup-mode).
477
478## Browser Compatibility
479
480We ensure browser compatibility in Chrome, Safari, Firefox and IE >= 10. We currently use [zuul](https://github.com/defunctzombie/zuul) along with [Saucelabs](https://saucelabs.com) to run integration tests on each push.
481
482## Issue Reporting
483
484If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
485
486## Author
487
488[Auth0](auth0.com)
489
490## License
491
492This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.
493
494
495[circleci-image]: https://img.shields.io/circleci/project/github/auth0/lock.svg?style=flat-square
496[circleci-url]: https://circleci.com/gh/auth0/lock/tree/master
497[npm-image]: https://img.shields.io/npm/v/auth0-lock.svg?style=flat-square
498[npm-url]: https://npmjs.org/package/auth0-lock
499[license-image]: http://img.shields.io/npm/l/auth0-lock.svg?style=flat-square
500[license-url]: #license
501[downloads-image]: http://img.shields.io/npm/dm/auth0-lock.svg?style=flat-square
502[downloads-url]: https://npmjs.org/package/auth0-lock
503[david-image]: https://david-dm.org/auth0/lock/status.svg?style=flat-square
504[david-url]: https://david-dm.org/auth0/lock