ngrok验证auth
There are a lot of great tools out there for creating modern apps that can often make our lives easier, but one aspect that is often tricky and time-consuming is authentication. The landscape around building applications today is different than it used to be, which can make it difficult to use traditional methods of authentication effectively. Added to this is an increased desire for authentication features that are more recent in their conception--things like multifactor auth, single sign-on, and password-less login. Let's take a closer look at some of these.
有很多很棒的工具可以用来创建现代应用程序,这些应用程序通常可以使我们的生活更轻松,但是身份验证通常是棘手且耗时的。 如今,构建应用程序的环境与以往不同,这可能使有效使用传统身份验证方法变得困难。 除此之外,人们对认证概念的最新要求也越来越高,例如多因素认证,单点登录和无密码登录。 让我们仔细看看其中的一些。
单页应用程序身份验证
Before single page apps were popular, authentication for the typical round-trip application wasn't that complicated: simply check the user's credentials against the database, save a session on the server, and return a cookie to the user. However, this traditional method of authentication isn't well-suited to single page apps that rely on data APIs because it necessitates that the API be stateful, which can have adverse effects. Instead, using stateless authentication methods like JSON Web Tokens is preferable, but comes at the cost of needing to keep various parts of the single page app synced up with some indication that the user is authenticated. This is typically done by checking whether the user's JWT is valid and then conditionally showing elements and restricting routes based on that result.
在单页应用程序流行之前,对于典型的双向应用程序的身份验证并不那么复杂:只需针对数据库检查用户的凭据,在服务器上保存会话,然后向用户返回cookie。 但是,这种传统的身份验证方法不适用于依赖数据API的单页应用程序,因为它要求API必须是有状态的,这可能会产生不利影响。 取而代之的是,使用诸如JSON Web令牌之类的无状态身份验证方法是可取的,但这样做的代价是需要保持单页应用程序的各个部分与用户已通过身份验证的指示保持同步。 通常,这是通过检查用户的JWT是否有效,然后有条件地显示元素并基于该结果限制路线来完成的。
社会认证
People want to be able to authenticate with their existing credentials from social providers like Google, Twitter, Facebook and the like. This option is great for users because it means they don't need to remember yet another set of credentials and businesses love it because it gives them a way to find out more about their customers. The downside, however, is that it can be difficult and time-consuming to implement authentication for each of the social identity providers that might be requested by the application's user base. There are open source projects out there like PassportJS that can make things easier on the developer, but even with a library, this can still be a cumbersome task that requires a fair bit of maintenance.
人们希望能够使用来自Google,Twitter,Facebook等社交提供商的现有凭据进行身份验证。 此选项对用户非常有用,因为这意味着他们不需要记住另一组凭据,而企业也喜欢它,因为它为他们提供了一种更多了解其客户的方式。 但是,不利的一面是,对于应用程序用户群可能要求的每个社会身份提供者实施身份验证可能会很困难且很耗时。 诸如PassportJS之类的开放源代码项目可以使开发人员更轻松,但是即使有了库,这仍然是一项繁琐的工作,需要大量维护。
额外的安全性
Businesses and users alike are increasingly demanding heightened security in applications, and extra measures like multifactor authentication can be very effective. The problem is that this feature isn't trivial. It can be difficult to implement and prone to errors when coding it by hand, and is certainly something that needs to be done right.
企业和用户都日益要求提高应用程序的安全性,诸如多因素身份验证之类的额外措施可能非常有效。 问题在于该功能并不简单。 手工编码时可能很难实现并且容易出错,并且肯定是需要正确完成的事情。
Auth0是实现身份验证的最简单方法
Auth0 takes all of the complexity out of authentication and makes identity easy for developers. With Auth0, you can add authentication to any app in under 10 minutes and implement features like social login, mutlifactor auth, and single sign-on at the flip of a switch. It really is the easiest way to add authentication to your app!
Auth0消除了身份验证的所有复杂性,并使开发人员易于识别。 使用Auth0,您可以在10分钟内将身份验证添加到任何应用程序,并在切换时实现社交登录,多因素身份验证和单点登录等功能。 这确实是向您的应用添加身份验证的最简单方法!
With Auth0, you get a production-ready free tier that gives you 7,000 regular active users at no cost. A regular active user is one that has logged in at some point in the last 30 days, which is only about 15% of the user base for a lot of companies.
借助Auth0,您将获得可用于生产的免费套餐,该套餐可免费为您提供7,000个常规活跃用户。 常规活动用户是过去30天内某个时间登录的用户,对于许多公司而言,它仅占用户总数的15%。
在React App中使用Auth0
To get an idea of how easy it is to add authentication to a modern app, let's build a simple one using React. This small application will allow users to log in and access proteced resources with the JSON Web Token (JWT) they receive back from Auth0.
为了了解向现代应用添加身份验证有多么容易,让我们使用React构建一个简单的应用。 这个小型应用程序将允许用户使用从Auth0收到的JSON Web令牌(JWT)登录并访问受保护的资源。
注册Auth0
To get started, sign up for a your free Auth0 account. Once you have signed up, head over to your management area and check out the Default App that gets created for you under the Applications link. This is where you can find some of the details that you'll need to make Auth0 work in your app, including your domain, client ID, and secret key.
首先,请注册一个免费的Auth0帐户 。 注册后,转到管理区域,并在“ 应用程序”链接下签出为您创建的默认应用 程序 。 在这里,您可以找到使Auth0在您的应用中正常工作所需的一些详细信息,包括您的域,客户端ID和密钥。
You'll also need to enter an allowed origin as you test out your app. To do this, simply enter http://localhost:<your-port>
in the Allowed Origins area within your app's settings.
在测试应用程序时,您还需要输入允许的来源。 为此,只需在应用程序设置的“ 允许的来源”区域中输入http://localhost:<your-port>
。
While you're in the management area, create a new user under the Users link so that you'll have some credentials to log in with later on.
在管理区域中时,请在“ 用户”链接下创建一个新用户,以便您拥有一些凭据以便以后登录。
将Auth0Lock添加到应用
Lock is the login box widget provided by Auth0 that allows you to have a fully-featured authentication screen by just dropping in a script tag. You can get Lock from Auth0's CDN and add it to your index.html
file.
Lock是Auth0提供的登录框小部件,只需放置一个脚本标签,即可使您拥有功能齐全的身份验证屏幕。 您可以从Auth0的CDN获取锁,并将其添加到index.html
文件中。
- <!-- index.html -->
-
- <!-- Auth0Lock script -->
- <script src="//cdn.auth0.com/js/lock-9.0.min.js"></script>
-
- <!-- Setting the right viewport -->
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
实例化组件中的锁定
The best place to configure Lock is in the componentWillMount
lifecycle hook. Add an instance of Lock to a root App
component and pass in your Auth0 details.
配置Lock的最佳位置是componentWillMount
生命周期挂钩。 将Lock实例添加到根App
组件,然后传递您的Auth0详细信息。
- // App.jsx
-
- var App = React.createClass({
- // ...
- componentWillMount: function() {
- this.lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_CLIENT_DOMAIN');
- },
- render: function() {
- return (<Home lock={this.lock} />);
- }
- });
显示锁定小部件
The lock
instance has been passed down to a component called Home
. To open up the Lock widget on a button click, create a new method called showLock
which calls lock.show()
.
lock
实例已传递到名为Home
的组件。 要在单击按钮时打开Lock小部件,请创建一个名为showLock
的新方法,该方法将调用lock.show()
。
- // Home.jsx
-
- var Home = React.createClass({
- // ...
- showLock: function() {
- // Show the Auth0Lock widget
- this.props.lock.show();
- },
-
- render: function() {
- return (
- <div className="login-box">
- <a onClick={this.showLock}>Sign In</a>
- </div>);
- }
- });
Now when the user clicks the Sign In button, they will see the Lock widget and be able to enter their credentials.
现在,当用户单击“ 登录”按钮时,他们将看到“ 锁定”小部件并能够输入其凭据。
If the user successfully authenticates, they are redirected back to the app with their JWT (named id_token
) as a hash. This JWT is signed with the secret key that is set in the application's settings and can now be used to gain access to protected resources on your server. But first, it needs to be set in local storage.
如果用户成功进行身份验证,则将其JWT(名为id_token
)作为哈希重定向到应用程序。 此JWT使用在应用程序设置中设置的密钥签名,现在可以用于访问服务器上受保护的资源。 但是首先,它需要在本地存储中设置。
保存用户的JWT
To use the JWT later on, it needs to be saved and accessed somehow. For that, a method that checks the URL hash for a token and saves it if one is present is needed.
要稍后使用JWT,需要以某种方式保存和访问它。 为此,需要一种方法来检查URL哈希中是否有令牌,并在存在令牌时将其保存。
- // App.jsx
-
- var App = React.createClass({
- componentWillMount: function() {
- ...
- // Set the state with a property that has the token
- this.setState({idToken: this.getIdToken()})
- },
- createLock: function() {
- this.lock = new Auth0Lock(this.props.clientId, this.props.domain);
- },
- getIdToken: function() {
- // First, check if there is already a JWT in local storage
- var idToken = localStorage.getItem('id_token');
- var authHash = this.lock.parseHash(window.location.hash);
- // If there is no JWT in local storage and there is one in the URL hash,
- // save it in local storage
- if (!idToken && authHash) {
- if (authHash.id_token) {
- idToken = authHash.id_token
- localStorage.setItem('id_token', authHash.id_token);
- }
- if (authHash.error) {
- // Handle any error conditions
- console.log("Error signing in", authHash);
- }
- }
- return idToken;
- },
- render: function() {
- if (this.state.idToken) {
- return (<LoggedIn lock={this.lock} idToken={this.state.idToken} />);
- } else {
- return (<Home lock={this.lock} />);
- }
- }
- });
This function checks for the presence of a JWT in local storage and also for one in the URL hash. If there's nothing in local storage and there is something in the URL hash, it saves the id_token
from the hash to local storage so that it can be used later.
此功能检查本地存储中是否存在JWT,以及URL哈希中是否存在JWT。 如果本地存储中没有任何内容,并且URL哈希中有内容,它将id_token
从哈希中保存到本地存储中,以便以后使用。
Note: This implementation uses
redirect
mode, but you can also usepopup
mode which gives you the user's profile and token in a callback instead of redirecting and providing it in a hash. See the Auth0Lock documentation for more detail.注意:此实现使用
redirect
模式,但是您也可以使用popup
模式,该模式在回调中为您提供用户的个人资料和令牌,而不是重定向并在哈希中提供。 有关更多详细信息,请参见Auth0Lock文档 。
显示用户资料
Auth0Lock comes with a method that accepts the user's JWT and returns his or her profile. The profile object that gets returned has some useful information like the user's nickname, email, and avatar URL, and we can use this to make a profile page. Let's do this in a component called LoggedIn
.
Auth0Lock带有一种接受用户JWT并返回其个人资料的方法。 返回的个人资料对象包含一些有用的信息,例如用户的昵称,电子邮件和头像URL,我们可以使用它来创建个人资料页面。 让我们在名为LoggedIn
的组件中执行此LoggedIn
。
- // LoggedIn.jsx
-
- var LoggedIn = React.createClass({
- getInitialState: function() {
- return {
- profile: null
- }
- },
-
- componentDidMount: function() {
- // The token is passed down from the App component
- // and used to retrieve the profile
- this.props.lock.getProfile(this.props.idToken, function (err, profile) {
- if (err) {
- console.log("Error loading the Profile", err);
- return;
- }
- this.setState({profile: profile});
- }.bind(this));
- },
-
- render: function() {
- if (this.state.profile) {
- return (
- <img src={this.state.profile.picture} />
- <h2>Welcome {this.state.profile.nickname}</h2>
- );
- } else {
- return (
- <div className="loading">Loading profile</div>
- );
- }
- }
- });
对API进行安全调用
Of course, one of the biggest reasons for authentication is to access protected resources. The first step in protecting API endpoints is to set up a middleware on your server that uses your app's secret key to check incoming JWTs. With the user's JWT saved in local storage, you can then make calls to your protected endpoints and send the token along to be checked for validity.
当然,进行身份验证的最大原因之一就是访问受保护的资源。 保护API端点的第一步是在服务器上设置一个中间件,该中间件使用应用程序的密钥检查传入的JWT。 将用户的JWT保存在本地存储中之后,您便可以调用受保护的端点,并发送令牌以进行有效性检查。
Check out this seed project for a quick example of how to set up an Express app up with JWT middleware.
查看此种子项目 ,以获取有关如何使用JWT中间件设置Express应用程序的快速示例。
The method for sending XHR requests to the backend is up to you, as long as you can attach a custom header. Using the fetch API, it's as simple as passing in an object with some configuration.
只要您可以附加自定义标头,就可以将XHR请求发送到后端的方法由您决定。 使用fetch API ,就像传递带有某种配置的对象一样简单。
- // LoggedIn.jsx
-
- ...
- callApi: function() {
- var getFoos = fetch('/api/foos', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('id_token')
- },
- method: 'GET',
- cache: false
- });
-
- getFoos.then(function (response) {
- response.json().then(function (foos) {
- // Put the results on a property
- // to be displayed in the view
- console.log('the foos:', foos);
- });
- });
- }
- ...
The user's JWT gets sent as an Authorization
header with the Bearer
scheme.
用户的JWT与Bearer
方案一起作为Authorization
标头发送。
注销用户
Logging out is as simple as removing the user's JWT from local storage.
注销就像从本地存储中删除用户的JWT一样简单。
- localStorage.removeItem('id_token');
- // Redirect to the home route
Note: Even though the token is removed from local storage, it is still valid until it expires. Keep your token lifetimes short to avoid security breaches and consider using a JTI to blacklist tokens. Token expiry can be controlled in your application's settings in the management area.
注意:即使令牌已从本地存储中删除,它仍然有效,直到过期。 为了避免安全漏洞,请尽量缩短令牌寿命,并考虑使用JTI将令牌列入黑名单 。 令牌到期可以在管理区域中应用程序的设置中进行控制。
附加功能示例:启用社交提供程序和多因素身份验证
With Auth0 it's easy to use any social identity provider and enable extra security features like multifactor authentication.
使用Auth0,可以轻松使用任何社交身份提供商并启用额外的安全功能,例如多因素身份验证。
From your management area, head over to the Connections > Social link and flip the switch to the on position for any that you like.
在您的管理区域中,转到“ 连接” >“ 社交”链接,然后将任意开关切换到打开位置。
You can also enable multifactor authentication from the Multifactor Auth link. Once you select either Google Authenticator or Duo as your MFA provider, simply drop the client ID for your app into the CLIENTS_WITH_MFA
array that comes up in the code snippet. Now when your users log in, they will be required to go through the two-step authentication process once every 30 days.
您还可以从“多重身份验证”链接启用多重身份验证 。 选择Google Authenticator或Duo作为MFA提供者后,只需将应用程序的客户端ID拖放到代码段中的CLIENTS_WITH_MFA
数组中即可。 现在,当您的用户登录时,将要求他们每30天执行一次两步身份验证过程。
那Redux呢?
Auth0 is totally agnostic about how you construct your applications--as long as it's JavaScript for the front end, you're good to go. To get an idea of how to add Auth0 to your Redux application, checkout this article on the subject, as well as the corresponding repo.
Auth0完全不了解您如何构建应用程序-只要它是前端JavaScript,您就可以开始使用。 要了解如何将Auth0添加到Redux应用程序中,请查看关于此主题的本文以及相应的repo 。
结语
Implementing a proper authentication system for modern apps and including extra features like social login, multifactor authentication, and others can be tricky and is often time consuming. Fortunately, Auth0 provides a drop-in solution that takes out all the complexity and allows you to focus your effort on developing your actual application. JSON Web Tokens offer a stateless method of authenticating users and protecting API endpoints, and this is the perfect solution for single page apps like those built with React.
为现代应用程序实施适当的身份验证系统,包括社交登录,多因素身份验证等其他功能可能很棘手,而且通常很耗时。 幸运的是, Auth0提供了一种嵌入式解决方案,可以消除所有复杂性,并使您可以将精力集中在开发实际的应用程序上。 JSON Web令牌提供了一种无状态的方法来验证用户身份并保护API端点,这对于单页面应用程序(例如使用React构建的应用程序)是完美的解决方案。
For further details on implementing Auth0 in a React app, head over to the documentation. You can also checkout the quickstart docs to find SDKs and samples for all popular front-end, backend, and mobile libraries and frameworks. Here's a sample of what's available:
有关在React应用中实现Auth0的更多详细信息,请转到文档 。 您还可以查看快速入门文档,以找到所有流行的前端,后端以及移动库和框架的SDK和示例。 以下是可用示例:
前端
后端
移动
ngrok验证auth