@aaxis/auth0-spa-js 中文文档教程

发布于 3年前 浏览 32 项目主页 更新于 3年前

Modify auth0 js to add WSO2 support

<script src="auth0-spa-js.production.js"></script>

<button id="login">Click to Login</button>
<button id="logout">Logout</button>
<button id="call-api">Refresh Token</button>

<script>
  const auth0 = new Auth0Client({
    domain: 'accounts.XXXX.com',
    client_id: 'xxxxxxxxx',
    redirect_uri: 'https://xxxxxx/callback',
    scope: 'openid',
    advancedOptions: {
      logoutPath: '/oidc/logout',
      tokenPath: '/oauth2/token',
      loginPath: '/oauth2/authorize',
      contentType: 'application/x-www-form-urlencoded'
    }
  });

  document.getElementById('login').addEventListener('click', async () => {
    await auth0.loginWithRedirect();
  });

  document.getElementById('logout').addEventListener('click', async () => {
    await auth0.logout({
      returnTo: 'https://xxxxxx.com/'
    });
  });

  document.getElementById('call-api').addEventListener('click', async () => {
    const accessToken = await auth0.getTokenSilently();
    console.log(accessToken);
  });

  //in your callback route (<MY_CALLBACK_URL>)
  window.addEventListener('load', async () => {
    const redirectResult = await auth0.handleRedirectCallback();
    //logged in. you can get the user profile like this:
    const user = await auth0.getUser();
    console.log(user);
  });

</script>

Refer to @auth0/auth0-spa-js

使用 使用 PKCE 的授权代码授予流程 的单页应用程序的 Auth0 SDK。

CircleCI发布 Codecov下载 许可证

Table of Contents

Documentation

Installation

来自 CDN:

<script src="https://cdn.auth0.com/js/auth0-spa-js/1.13/auth0-spa-js.production.js"></script>

使用 npm

npm install @auth0/auth0-spa-js

使用 yarn

yarn add @auth0/auth0-spa-js

Getting Started

Creating the client

在呈现或初始化您的应用程序之前创建一个 Auth0Client 实例。 您应该只有一个客户端实例。

import createAuth0Client from '@auth0/auth0-spa-js';

//with async/await
const auth0 = await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>'
});

//with promises
createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>'
}).then(auth0 => {
  //...
});

//or, you can just instantiate the client on it's own
import { Auth0Client } from '@auth0/auth0-spa-js';

const auth0 = new Auth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>'
});

//if you do this, you'll need to check the session yourself
try {
  await getTokenSilently();
} catch (error) {
  if (error.error !== 'login_required') {
    throw error;
  }
}

1 - Login

<button id="login">Click to Login</button>
//with async/await

//redirect to the Universal Login Page
document.getElementById('login').addEventListener('click', async () => {
  await auth0.loginWithRedirect();
});

//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', async () => {
  const redirectResult = await auth0.handleRedirectCallback();
  //logged in. you can get the user profile like this:
  const user = await auth0.getUser();
  console.log(user);
});

//with promises

//redirect to the Universal Login Page
document.getElementById('login').addEventListener('click', () => {
  auth0.loginWithRedirect().catch(() => {
    //error while redirecting the user
  });
});

//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', () => {
  auth0.handleRedirectCallback().then(redirectResult => {
    //logged in. you can get the user profile like this:
    auth0.getUser().then(user => {
      console.log(user);
    });
  });
});

2 - Calling an API

<button id="call-api">Call an API</button>
//with async/await
document.getElementById('call-api').addEventListener('click', async () => {
  const accessToken = await auth0.getTokenSilently();
  const result = await fetch('https://myapi.com', {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${accessToken}`
    }
  });
  const data = await result.json();
  console.log(data);
});

//with promises
document.getElementById('call-api').addEventListener('click', () => {
  auth0
    .getTokenSilently()
    .then(accessToken =>
      fetch('https://myapi.com', {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      })
    )
    .then(result => result.json())
    .then(data => {
      console.log(data);
    });
});

3 - Logout

<button id="logout">Logout</button>
import createAuth0Client from '@auth0/auth0-spa-js';

document.getElementById('logout').addEventListener('click', () => {
  auth0.logout();
});

您可以在注销后将用户重定向回您的应用程序。 此 URL 必须出现在Auth0 仪表板中应用的允许注销 URL 设置中:

auth0.logout({
  returnTo: 'https://your.custom.url.example.com/'
});

Data caching options

可以配置 SDK在内存或本地存储中缓存 ID 令牌和访问令牌。 默认在内存中。 创建 Auth0 客户端时,可以使用 cacheLocation 选项控制此设置。

要使用内存模式,不需要额外的选项,因为这是默认设置。 要将 SDK 配置为使用本地存储缓存数据,请按如下方式设置 cacheLocation

await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>',
  cacheLocation: 'localstorage' // valid values are: 'memory' or 'localstorage'
});

重要提示:此功能将允许缓存数据如 ID 和访问令牌< /strong> 存储在本地存储中。 执行此选项会更改应用程序的安全特性,不应轻易使用。 应格外小心以减轻 XSS 攻击并将令牌从本地存储中被盗的风险降至最低。

Refresh Tokens

刷新令牌可用于请求新的访问令牌。 详细了解我们的刷新令牌如何用于基于浏览器的应用程序,以帮助您决定是否你需要使用它们。

要启用刷新令牌,请将 useRefreshTokens 选项设置为 true

await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>',
  useRefreshTokens: true
});

使用此设置将导致 SDK 自动将 offline_access 范围发送到授权服务器。 然后刷新令牌将用于交换新的访问令牌,而不是使用隐藏的 iframe,并直接调用 /oauth/token 端点。 这意味着在大多数情况下,SDK 在使用刷新令牌时不依赖第三方 cookie。

注意 此配置选项需要为您的 Auth0 租户启用旋转刷新令牌

Refresh Token fallback

在刷新令牌不可用的所有情况下,SDK 都会回退到使用带有 prompt=none 的隐藏 iframe 的传统技术来尝试获取新的访问令牌和刷新令牌。 例如,如果您正在使用内存缓存并且您已刷新页面,就会发生这种情况。 在这种情况下,之前存储的任何刷新令牌都将丢失。

如果回退机制失败,将抛出一个 login_required 错误,并且可以进行处理以使用户重新通过身份验证过程。

注意:此回退机制仍然需要访问 Auth0 会话 cookie,因此如果第三方 cookie 被阻止,则此回退将不起作用,用户必须重新验证才能获得新的刷新令牌。

Organizations

Organizations 是一组功能,可为构建和维护 SaaS 和企业对企业 (B2B) 应用程序的开发人员提供更好的支持。

使用组织,您可以: 将

  • 团队、业务客户、合作伙伴公司或任何逻辑上的用户组表示为组织,这些用户应该具有不同的访问应用程序的方式。

  • 以多种方式管理他们的会员资格,包括用户邀请。

  • 为每个组织配置品牌联合登录流程。

  • 实施基于角色的访问控制,以便用户在不同组织的上下文中进行身份验证时可以具有不同的角色。

  • 使用组织 API 在您的产品中构建管理功能,以便这些企业可以管理自己的组织。

请注意,Organizations 目前仅适用于我们的 Enterprise 和 Startup 订阅计划的客户。

Log in to an organization

通过在设置客户端时指定organization 参数来登录组织:

createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>',
  organization: '<MY_ORG_ID>'
});

您也可以在登录时指定组织:

// Using a redirect
client.loginWithRedirect({
  organization: '<MY_ORG_ID>'
});

// Using a popup window
client.loginWithPopup({
  organization: '<MY_ORG_ID>'
});

Accept user invitations

通过在您的应用程序中创建一个可以处理的路由来接受通过 SDK 的用户邀请用户邀请 URL,并通过从该 URL 传递 organizationinvitation 参数使用户登录。 您可以根据需要使用 loginWithRedirectloginWithPopup

const url = new URL(invitationUrl);
const params = new URLSearchParams(url.search);
const organization = params.get('organization');
const invitation = params.get('invitation');

if (organization && invitation) {
  client.loginWithRedirect({
    organization,
    invitation
  });
}

Advanced options

在配置 Auth0Client 时,可以通过指定 advancedOptions 属性来设置高级选项。 在 API 文档中了解完整的高级选项

createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  advancedOptions: {
    defaultScope: 'email' // change the scopes that are applied to every authz request. **Note**: `openid` is always specified regardless of this setting
  }
});

Contributing

集这个回购! 在开始之前,请参阅以下内容:

Support + Feedback

如需支持或提供反馈,请在我们的问题跟踪器上提出问题< /a>。

Frequently Asked Questions

有关使用 SDK 时可能遇到的常见问题的概要,请查看常见问题解答< /a>。

Vulnerability Reporting

请不要在公共 GitHub 问题跟踪器上报告安全漏洞。  负责任的披露计划 详细说明了披露安全问题的程序。

What is Auth0?

Auth0 可帮助您轻松地:

  • implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
  • log in users with username/password databases, passwordless, or multi-factor authentication
  • link multiple user accounts together
  • generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
  • access demographics and analytics detailing how, when, and where users are logging in
  • enrich user profiles from other data sources using customizable JavaScript rules

为什么选择 Auth0?

License

该项目已获得 MIT 许可。 有关详细信息,请参阅 LICENSE 文件。

Modify auth0 js to add WSO2 support

<script src="auth0-spa-js.production.js"></script>

<button id="login">Click to Login</button>
<button id="logout">Logout</button>
<button id="call-api">Refresh Token</button>

<script>
  const auth0 = new Auth0Client({
    domain: 'accounts.XXXX.com',
    client_id: 'xxxxxxxxx',
    redirect_uri: 'https://xxxxxx/callback',
    scope: 'openid',
    advancedOptions: {
      logoutPath: '/oidc/logout',
      tokenPath: '/oauth2/token',
      loginPath: '/oauth2/authorize',
      contentType: 'application/x-www-form-urlencoded'
    }
  });

  document.getElementById('login').addEventListener('click', async () => {
    await auth0.loginWithRedirect();
  });

  document.getElementById('logout').addEventListener('click', async () => {
    await auth0.logout({
      returnTo: 'https://xxxxxx.com/'
    });
  });

  document.getElementById('call-api').addEventListener('click', async () => {
    const accessToken = await auth0.getTokenSilently();
    console.log(accessToken);
  });

  //in your callback route (<MY_CALLBACK_URL>)
  window.addEventListener('load', async () => {
    const redirectResult = await auth0.handleRedirectCallback();
    //logged in. you can get the user profile like this:
    const user = await auth0.getUser();
    console.log(user);
  });

</script>

Refer to @auth0/auth0-spa-js

Auth0 SDK for Single Page Applications using Authorization Code Grant Flow with PKCE.

CircleCIRelease CodecovDownloads License

Table of Contents

Documentation

Installation

From the CDN:

<script src="https://cdn.auth0.com/js/auth0-spa-js/1.13/auth0-spa-js.production.js"></script>

Using npm:

npm install @auth0/auth0-spa-js

Using yarn:

yarn add @auth0/auth0-spa-js

Getting Started

Creating the client

Create an Auth0Client instance before rendering or initializing your application. You should only have one instance of the client.

import createAuth0Client from '@auth0/auth0-spa-js';

//with async/await
const auth0 = await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>'
});

//with promises
createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>'
}).then(auth0 => {
  //...
});

//or, you can just instantiate the client on it's own
import { Auth0Client } from '@auth0/auth0-spa-js';

const auth0 = new Auth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>'
});

//if you do this, you'll need to check the session yourself
try {
  await getTokenSilently();
} catch (error) {
  if (error.error !== 'login_required') {
    throw error;
  }
}

1 - Login

<button id="login">Click to Login</button>
//with async/await

//redirect to the Universal Login Page
document.getElementById('login').addEventListener('click', async () => {
  await auth0.loginWithRedirect();
});

//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', async () => {
  const redirectResult = await auth0.handleRedirectCallback();
  //logged in. you can get the user profile like this:
  const user = await auth0.getUser();
  console.log(user);
});

//with promises

//redirect to the Universal Login Page
document.getElementById('login').addEventListener('click', () => {
  auth0.loginWithRedirect().catch(() => {
    //error while redirecting the user
  });
});

//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', () => {
  auth0.handleRedirectCallback().then(redirectResult => {
    //logged in. you can get the user profile like this:
    auth0.getUser().then(user => {
      console.log(user);
    });
  });
});

2 - Calling an API

<button id="call-api">Call an API</button>
//with async/await
document.getElementById('call-api').addEventListener('click', async () => {
  const accessToken = await auth0.getTokenSilently();
  const result = await fetch('https://myapi.com', {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${accessToken}`
    }
  });
  const data = await result.json();
  console.log(data);
});

//with promises
document.getElementById('call-api').addEventListener('click', () => {
  auth0
    .getTokenSilently()
    .then(accessToken =>
      fetch('https://myapi.com', {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      })
    )
    .then(result => result.json())
    .then(data => {
      console.log(data);
    });
});

3 - Logout

<button id="logout">Logout</button>
import createAuth0Client from '@auth0/auth0-spa-js';

document.getElementById('logout').addEventListener('click', () => {
  auth0.logout();
});

You can redirect users back to your app after logging out. This URL must appear in the Allowed Logout URLs setting for the app in your Auth0 Dashboard:

auth0.logout({
  returnTo: 'https://your.custom.url.example.com/'
});

Data caching options

The SDK can be configured to cache ID tokens and access tokens either in memory or in local storage. The default is in memory. This setting can be controlled using the cacheLocation option when creating the Auth0 client.

To use the in-memory mode, no additional options need are required as this is the default setting. To configure the SDK to cache data using local storage, set cacheLocation as follows:

await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>',
  cacheLocation: 'localstorage' // valid values are: 'memory' or 'localstorage'
});

Important: This feature will allow the caching of data such as ID and access tokens to be stored in local storage. Exercising this option changes the security characteristics of your application and should not be used lightly. Extra care should be taken to mitigate against XSS attacks and minimize the risk of tokens being stolen from local storage.

Refresh Tokens

Refresh tokens can be used to request new access tokens. Read more about how our refresh tokens work for browser-based applications to help you decide whether or not you need to use them.

To enable the use of refresh tokens, set the useRefreshTokens option to true:

await createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>',
  useRefreshTokens: true
});

Using this setting will cause the SDK to automatically send the offline_access scope to the authorization server. Refresh tokens will then be used to exchange for new access tokens instead of using a hidden iframe, and calls the /oauth/token endpoint directly. This means that in most cases the SDK does not rely on third-party cookies when using refresh tokens.

Note This configuration option requires Rotating Refresh Tokens to be enabled for your Auth0 Tenant.

Refresh Token fallback

In all cases where a refresh token is not available, the SDK falls back to the legacy technique of using a hidden iframe with prompt=none to try and get a new access token and refresh token. This scenario would occur for example if you are using the in-memory cache and you have refreshed the page. In this case, any refresh token that was stored previously would be lost.

If the fallback mechanism fails, a login_required error will be thrown and could be handled in order to put the user back through the authentication process.

Note: This fallback mechanism does still require access to the Auth0 session cookie, so if third-party cookies are being blocked then this fallback will not work and the user must re-authenticate in order to get a new refresh token.

Organizations

Organizations is a set of features that provide better support for developers who build and maintain SaaS and Business-to-Business (B2B) applications.

Using Organizations, you can:

  • Represent teams, business customers, partner companies, or any logical grouping of users that should have different ways of accessing your applications, as organizations.

  • Manage their membership in a variety of ways, including user invitation.

  • Configure branded, federated login flows for each organization.

  • Implement role-based access control, such that users can have different roles when authenticating in the context of different organizations.

  • Build administration capabilities into your products, using Organizations APIs, so that those businesses can manage their own organizations.

Note that Organizations is currently only available to customers on our Enterprise and Startup subscription plans.

Log in to an organization

Log in to an organization by specifying the organization parameter when setting up the client:

createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  redirect_uri: '<MY_CALLBACK_URL>',
  organization: '<MY_ORG_ID>'
});

You can also specify the organization when logging in:

// Using a redirect
client.loginWithRedirect({
  organization: '<MY_ORG_ID>'
});

// Using a popup window
client.loginWithPopup({
  organization: '<MY_ORG_ID>'
});

Accept user invitations

Accept a user invitation through the SDK by creating a route within your application that can handle the user invitation URL, and log the user in by passing the organization and invitation parameters from this URL. You can either use loginWithRedirect or loginWithPopup as needed.

const url = new URL(invitationUrl);
const params = new URLSearchParams(url.search);
const organization = params.get('organization');
const invitation = params.get('invitation');

if (organization && invitation) {
  client.loginWithRedirect({
    organization,
    invitation
  });
}

Advanced options

Advanced options can be set by specifying the advancedOptions property when configuring Auth0Client. Learn about the complete set of advanced options in the API documentation

createAuth0Client({
  domain: '<AUTH0_DOMAIN>',
  client_id: '<AUTH0_CLIENT_ID>',
  advancedOptions: {
    defaultScope: 'email' // change the scopes that are applied to every authz request. **Note**: `openid` is always specified regardless of this setting
  }
});

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Support + Feedback

For support or to provide feedback, please raise an issue on our issue tracker.

Frequently Asked Questions

For a rundown of common issues you might encounter when using the SDK, please check out the FAQ.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 helps you to easily:

  • implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
  • log in users with username/password databases, passwordless, or multi-factor authentication
  • link multiple user accounts together
  • generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
  • access demographics and analytics detailing how, when, and where users are logging in
  • enrich user profiles from other data sources using customizable JavaScript rules

Why Auth0?

License

This project is licensed under the MIT license. See the LICENSE file for more info.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文