vert.x和koa_如何通过五个步骤使用Vert.x,VueJS和OAuth2创建应用程序样板

vert.x和koa

by Thomas Reinecke

由托马斯·雷内克(Thomas Reinecke)

如何通过五个步骤使用Vert.x,VueJS和OAuth2创建应用程序样板 (How to create application boilerplate with Vert.x, VueJS, and OAuth2 in five steps)

In this tutorial you will learn how to setup an application boilerplate based on Vert.x (Java) as a backend and VueJs as a frontend with a focus on User Authentication against Keycloak through OAuth2. Once a User is logged in, the vertx-vue-keycloak app also demonstrates how to query the Vert.x backend, send data (mutations) and how Publish/Subscribe works between Vert.x and VueJS.

在本教程中,您将学习如何设置基于Vert.x(Java)作为后端和VueJs作为前端的应用程序样板,重点是通过OAuth2针对Keycloak进行用户身份验证。 一旦用户登录, vertx-vue-keycloak应用程序还将演示如何查询Vert.x后端,发送数据(突变)以及在Vert.x和VueJS之间进行发布/订阅的工作方式。

The e2e code for this article is hosted on GH here.

本文中的端到端代码在GH托管在这里

第1步-准备工作 (Step 1 — Prep Work)

安装KeyCloak (Install KeyCloak)

In this example we’re going to use Keycloak as Authentication and Authorization management provider. Keycloak is an open source identity and access management offering by RedHat, which provides OAuth2 and much more. Keycloak comes with a Web admin console to administrate the server. We can easily run it based on docker:

在此示例中,我们将使用Keycloak作为身份验证和授权管理提供程序。 Keycloak是RedHat提供的开放源代码身份和访问管理产品,它提供OAuth2等。 Keycloak带有Web管理控制台,用于管理服务器。 我们可以轻松地基于docker运行它:

docker run -d — name keycloak -p 38080:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -e KEYCLOAK_LOGLEVEL=DEBUG jboss/keycloak

After starting this container, the Keycloak admin console will be available at http://127.0.0.1:38080. Be aware of the version of Keycloak — at the time this article was written it was 4.5.0.Final, so the UI might look a little different with newer or earlier versions.

启动此容器后,可以在http://127.0.0.1:38080上使用Keycloak管理控制台。 请注意Keycloak的版本-在撰写本文时为4.5.0.Final ,因此UI可能与较新或较早的版本有所不同。

创建Keycloak客户端凭据 (Create the Keycloak client credential)

For the Vert.x app we’re going to develop, we need a registered client in Keycloak. Fill out the form with the given highlighted values:

对于我们将要开发的Vert.x应用程序,我们需要在Keycloak中注册的客户端。 用给定的突出显示值填写表单:

Save this, open and inspect the just created vertx-account client object:

保存此内容,打开并检查刚刚创建的vertx-account客户端对象:

We’ll come back to this page, in particular the information on the Credentials tab later when we embed the client details in the vertx code.

当我们在vertx代码中嵌入客户端详细信息时,我们将返回此页面,尤其是“ 凭据”选项卡上的信息。

创建角色 (Create Roles)

On the Roles Tab from the left sidebar in Keycloak, create two exemplary roles modify-account and view-account:

在Keycloak左侧栏中的“角色”标签上,创建两个示例性角色Modify -accountview-account

创建一个用户 (Create a User)

On the Manage Users tab, create a new user, give it a username testuser and an email address test@tester.com and save it:

在“管理用户”选项卡上,创建一个新用户,为其提供用户名testuser和电子邮件地址test@tester.com并保存:

Still on the just created users page, switch to the Credentials tab and set the password of this user to test. Also unselect the Temporary switch and click the Reset Password button. Be aware: the behaviour of this UI is a little strange. When you click this button, the Temporary flag switches back to true, but just ignore this. The password you gave should be well set.

仍在刚刚创建的用户页面上,切换到“凭据”选项卡,然后设置该用户的密码进行测试。 还要取消选择“ 临时”开关,然后单击“ 重置密码”按钮。 请注意:此UI的行为有些奇怪。 当您单击此按钮时, Temporary标志将切换回true,但是请忽略此设置。 您提供的密码应该设置正确。

Switch to the Role Mapping tab and assign the just created roles modify-account and view-account to this user:

切换到“角色映射”选项卡,并将刚创建的角色Modify-accountview-account分配给该用户:

This completes the setup of Keycloak. Congratulations! We’re now ready to work on our vert.x backend and VueJS frontend.

这样就完成了Keycloak的设置。 恭喜你! 现在,我们准备在vert.x后端和VueJS前端上工作。

More details on setting up Keycloak and configuring it for Vert.x can be found in this great article, which I also used as source for above instructions (thanks to Piotr Minkowski).

这篇很棒的文章中可以找到有关设置Keycloak并为Vert.x进行配置的更多详细信息,我也将其用作上述说明的来源(感谢Piotr Minkowski)

第2步-创建Vert.x后端和VueJs前端 (Step 2 — Create Vert.x Backend and VueJs Frontend)

I used Eclipse to create a simple Maven project (without archtype selection) and from there I added vertx onto the dependency list in pom.xml. At the time this article was written, vertx was on version 3.5.4.

我使用Eclipse创建了一个简单的Maven项目(没有选择archtype),然后从其中将vertx添加到pom.xml的依赖项列表中。 在撰写本文时,vertx的版本为3.5.4。

Clone the following repository (including the source-code for this article):

克隆以下存储库(包括本文的源代码):

vertx-stack/vertx-vue-keycloakContribute to vertx-stack/vertx-vue-keycloak development by creating an account on GitHub.github.com

vertx-stack / vertx-vue-keycloak 通过在GitHub上创建一个帐户来为vertx-stack / vertx-vue-keycloak开发 做出 贡献。 github.com

git clone https://github.com/vertx-stack/vertx-vue-keycloak.git
创建密钥库文件 (Create Keystore file)

You may want to follow whatever procedure you find appropriate to create a proper certificate chain and get it into the jks format. The example I give here is based on a self-signed certificate and it works great on local or for test environments. The repo you just cloned comes with the file, so you may skip this section. For production, please get a CA-signed certificate (a free one, for example, from LetsEncrypt).

您可能想按照您认为合适的任何步骤来创建正确的证书链并将其转换为jks格式。 我在此处给出的示例基于自签名证书,并且在本地或测试环境中都非常有效。 您刚刚克隆的存储库随文件一起提供,因此您可以跳过此部分。 对于生产,请获取CA签名的证书(例如,从LetsEncrypt获得的免费证书)。

Run the following OpenSSL command to generate your private key and public certificate. Use “testpassword” as password and leave all values default (hit enter until you’re through):

运行以下OpenSSL命令以生成您的私钥和公共证书。 使用“ testpassword ”作为密码,并将所有值保留为默认值(按回车直到完成):

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

Review the certificate file:

查看证书文件:

openssl x509 -text -noout -in cert.pem

Combine your key and certificate in a PKCS#12 (P12) bundle, and as the export password use “testpassword” again:

将您的密钥和证书合并到PKCS#12(P12)软件包中,并作为导出密码再次使用“ testpassword ”:

openssl pkcs12 -inkey key.pem -in cert.pem -export -out certificate.p12

Convert it into a JKS file. Use “testpassword” as the destination keystore password:

将其转换为JKS文件。 使用“ testpassword ”作为目标密钥库密码:

keytool -importkeystore -srckeystore certificate.p12 -srcstoretype pkcs12 -destkeystore test.jks -deststoretype jks

We now have our certificate store in test.jks, ready for use by vert.x to secure an HTTPS connection. This file also comes with the repo you just cloned.

现在,我们的证书存储位于test.jks中,可以由vert.x使用以保护HTTPS连接。 该文件还附带您刚刚克隆的存储库。

了解vertx-vue-keycloak应用 (Understand the vertx-vue-keycloak app)

The app contains both the vertx source codes for the backend and the VueJS-based frontend code.

该应用程序同时包含后端的vertx源代码和基于VueJS的前端代码。

On the Backend (src/main/java), the MainVerticle.java is primary entry point. It’s a Vertx verticle that is creating the HTTP/HTTPS server, configuring the various routes, exposing the /login endpoint that’s integrating with Keycloak, and finally is providing the API endpoints for our frontend.

后端 (src / main / java)上, MainVerticle.java是主要入口点。 这是一个Vertx垂直版本,用于创建HTTP / HTTPS服务器,配置各种路由,公开与Keycloak集成的/ login端点,最后为前端提供API端点。

The Frontend (placed in src/main/frontend) is a regular VueJS frontend that was created with the VueJS CLI. It’s containing the assets, libraries and components.

前端(放置在src / main / frontend中)是使用VueJS CLI创建的常规VueJS前端。 它包含资产,库和组件。

步骤3 —与KeyCloak集成 (Step 3 — Integrate with KeyCloak)

Open src/main/java/backend/MainVerticle.java and inspect the method createHttpServerAndRoutes:

打开src / main / java / backend / MainVerticle.java并检查方法createHttpServerAndRoutes:

JsonObject keycloakJson = new JsonObject()  .put("realm", "master")   .put("realm-public-key", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqZeGGDeEHmmUN4/UXh2gQD0yZEZirprsrdYK7GfcE1+QF9yfYfBrIv5cQUssFQKISVpbbLcoqYolsxcOvDyVFSQedHRsumOzqNZK38RHkidPMPrSNof5C3iMIHuXOCv/6exnLZvVoeYmkq42davYEz1tpSWzkZnlUMbRZFs1CfzLMM2rsAJWsO1/5zbDm0JhFl7EFUsTki72ihac1Q5zUUSFyf1jKUEkL7rrkYINjgAaQKktE8pnubc3Y44F5llY4YyU9/bqUWqMYDx868oiDcnoBpGGd4QrUMlbULZZLRqqUKK6iG1kHxDCJQ9gaCiJoELyAqXjnnO28OODQhxMHQIDAQAB")     .put("auth-server-url", "http://127.0.0.1:38080/auth")  .put("ssl-required", "external")  .put("resource", "vertx-account")  .put("credentials", new JsonObject()    . put("secret", "0c22e587-2ccb-4dd3-b017-5ff6a903891b"));
OAuth2Auth oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.PASSWORD, keycloakJson);

Get the realm and real-public-key from the Keycloak admin console. To get the key, click on the “Public Key” button on the Keys tab of the master realm:

从Keycloak管理控制台获取领域真实公钥 。 拿到钥匙后,点击境界的按键选项卡上的“公钥”按钮:

As a resource, include the previously created vertx-account client. As its credentials, navigate to it on the Clients menu > vertx-account > Credentials tab and copy the Secret from there:

作为资源,包括以前创建的vertx-account客户端。 作为其凭据,请在“客户端”菜单>“ vertx-account”>“凭据”选项卡上导航至该凭据,然后从此处复制密钥:

As the OAuth2FlowType we’re going to select PASSWORD, representing the Password Credentials Flow. More details on the OAuthFlows can be found here.

作为OAuth2FlowType,我们将选择PASSWORD,它表示密码凭证流 。 有关OAuthFlow的更多详细信息,请参见此处

We’re now able to define the /login route to handle the actual login:

现在,我们可以定义/ login路由来处理实际的登录:

We can now run our first test of the vertx Backend by starting the vert.x launcher. Using Postman, we can now run the first user auth via a POST against 127.0.0.1:8080/login (our vertx server with the /login route). On the Body, we select raw data and enter the following JSON object:

现在,我们可以通过启动vert.x启动器来运行vertx后端的第一个测试。 使用Postman,我们现在可以通过POST对127.0.0.1:8080/login (我们的具有/ login路由的vertx服务器)运行首次用户身份验证。 在主体上,我们选择原始数据,然后输入以下JSON对象:

{  "username":"testuser",   "password":"test",   "scope":"modify-account view-account"}

Press Send in Postman and send this to our vertx server:

在邮递员中按发送 ,然后将其发送到我们的vertx服务器:

The result on the server will look like this, indicating that we have successfully found the user “testuser” on Keycloak. Good job!

服务器上的结果将如下所示,表明我们已经在Keycloak上成功找到了用户“ testuser ”。 做得好!

通过我们的前端进行身份验证 (Authenticate with our Frontend)

Now that we have the basic Authentication working and have tested it with Postman, it’s time to get our Frontend app integrated with it. The Forntend comes at src/main/frontend. To get it going, run a quick install of the dependencies with yarn and finally start it with yarn dev. More Details here.

既然我们已经具备基本的身份验证功能,并且已经用Postman对其进行了测试,那么现在是时候将我们的Frontend应用程序与其集成在一起了。 Forntend位于src / main / frontend 。 为此,请使用yarn快速安装依赖项,最后使用yarn dev启动它。 更多细节在这里

The Frontend will now start on localhost:8081. It’s going to present a fairly simple login page (bootstrap was used to style it):

前端现在将从localhost:8081开始。 它将显示一个相当简单的登录页面(使用了引导程序来对其进行样式设置):

I wont go into all the specifics of this app here. For many more details on how this was created, please check out this great article from Paweł J. Wal.

我不会在这里进入这个程序的所有细节。 有关如何创建它的更多详细信息,请查阅PawełJ. Wal的 这篇出色文章

The only additional thing we need to change is to configure CORS on the Vert.x backend side to make sure the Frontend can speak to it.

我们唯一需要更改的就是在Vert.x后端配置CORS,以确保前端可以与之对话。

You’re now ready to authenticate a user from the VueJS Frontend App to your Vert.x backend. Logging in with your testuser:test gets you into the protected space of your app:

现在,您可以从VueJS前端应用程序向您的Vert.x后端进行身份验证了。 使用testuser:test登录可以进入应用程序的受保护空间:

Congratulations, you now have a pretty slick way to log into a VueJS app, running against a Vert.x API and Authentication server thats integrated with Keycloak.

恭喜,您现在可以使用一种巧妙的方法来登录VueJS应用,该应用可以在与Keycloak集成的Vert.x API和身份验证服务器上运行。

步骤4 —集成查询和数据更新逻辑 (Step 4 — Integrate Query and Data Update logic)

We’re going to implement a very simple message management system here as an example, which looks roughly like this:

作为示例,我们将在这里实现一个非常简单的消息管理系统,该系统大致如下所示:

The frontend and pieces of the eventbus integration in this example have been inspired by Mateusz Parzonka’s vertx-examples project on GitHub — thanks for that!

此示例中的eventbus集成的前端和片段受到了Mateusz Parzonka在GitHub上的vertx-examples项目的启发-谢谢!

The proposed procedure in this example is to utilize standard message endpoints, producers and consumers on the Vertx EventBus for a fully sophisticated Client/Server communication pattern including queries, data mutations and publish/subscribe. The idea is pretty simple:

在本示例中,建议的过程是利用Vertx EventBus上的标准消息终结点,生产者和使用者来实现包括查询,数据突变和发布/订阅在内的完全复杂的客户端/服务器通信模式。 这个想法很简单:

  • on the backend we expose a number of message consumers which act as get, create, and delete methods.

    在后端,我们公开了许多消息使用者,它们充当get,create和delete方法。
  • on the frontend we subscribe to specific data channels that allow us to send whatever from the backend to the frontend, which also greatly helps to tunnel client to client communication through the backend.

    在前端,我们订阅了特定的数据通道,这些通道允许我们将任何内容从后端发送到前端,这也大大有助于通过后端在客户端与客户端之间建立通信。

On the Frontend side, we’re going to create a vertx eventbus service that’s using vertx3-eventbus-client. The essential methods here are callApi and subscribe (for more details on pubsub, see step 5):

在前端,我们将创建一个使用vertx3-eventbus-client的vertx eventbus服务。 这里的基本方法是callApi订阅 (关于发布订阅的详细信息,请参阅第5步):

To get, delete and create a new message, inspect the Home.vue component, in particular the usage of the eventbus service from utils/eventbus:

要获取,删除和创建新消息,请检查Home.vue组件,尤其是utils / eventbus中eventbus服务的用法:

As a result, you’re now able to use this UI to receive the array of known messages from the backend, create new messages, and delete them. So far so good, but wait a minute: what’s actually happening to other clients that use the same app in parallel to me? Let’s dive into PubSub finally…

结果,您现在可以使用此UI从后端接收一系列已知消息,创建新消息并删除它们。 到目前为止一切顺利,但请稍等:与我并行使用同一应用程序的其他客户端实际上发生了什么? 让我们最后进入PubSub…

步骤5 —集成发布和订阅 (Step 5 — Integrate Publish & Subscribe)

We’ve already seen that the backend is publishing the full array of messages onto the Vertx EventBus whenever an update is made (which is a little bit of overkill, but let’s accept this for this example). How can the frontend finally catch these updates?

我们已经看到,无论何时进行更新,后端都会将所有消息发布到Vertx EventBus上(这有点过头了,但是在本示例中,我们接受它)。 前端如何最终捕获这些更新?

Fortunately the Vertx EventBus (which is based on SockJS) allows us to subscribe clients to channels that can be fueled by any other client (c2c communication) or also from the server.

幸运的是,Vertx EventBus(基于SockJS)允许我们为客户端订阅可以由任何其他客户端(c2c通信)或服务器提供的通道。

Our eventBus service provides a function to subscribe to such a channel (see the code above). This is being used again on the Home.vue component to capture changes on the message array and on the number of connections the vertx server is managing in the following way:

我们的eventBus服务提供了订阅此类频道的功能(请参见上面的代码)。 再次在Home.vue组件上使用它来捕获消息数组和vertx服务器正在通过以下方式管理的连接数上的更改:

Here we’re capturing the messages coming from the :pubsub/connections and :pubsub/messages channels and we’re pushing the incoming data into the frontend. This allows to keep multiple browsers that run the same app perfectly in sync through the vertx EventBus.

在这里,我们捕获来自:pubsub / connections:pubsub / messages通道的消息 ,并将传入的数据推送到前端。 这样可以使多个运行同一应用程序的浏览器通过vertx EventBus完美同步。

局限性 (Limitations)

One of the biggest limitations of this example is the setup of the vertx Backend. In particular the security on the vertx Eventbus is not yet configured, since we don’t check whether the user that’s calling the API is actually authenticated on the backend. So do not use this code for production apps without working on this.

此示例的最大限制之一是vertx后端的设置。 尤其是,尚未配置vertx Eventbus上的安全性,因为我们不检查调用API的用户是否在后端进行了实际身份验证。 因此,请勿在未进行任何处理的情况下将此代码用于生产应用程序。

Another aspect is that the EventBus and also the /login handler on the Backend still work over HTTP. The redirection to HTTPS code that’s in place only relates to the static resources, not yet to the EventBus as far I have tested with limited time. I guess since we don’t really serve static HTML content through vertx, it would make sense to disable the HTTP server completely and just go with HTTPS.

另一个方面是EventBus以及后端上的/ login处理程序仍然可以通过HTTP工作。 重定向到适当的HTTPS代码仅与静态资源有关,而与我在有限的时间内测试过的EventBus无关。 我猜是因为我们并不是真正通过vertx提供静态HTML内容,所以完全禁用HTTP服务器并仅使用HTTPS是有意义的。

Finally the HTTPS certificate was self-signed and certainly you don’t want to use this for serious use outside of localhost. Get yourself a CA-signed certificate (e.g. from LetsEncrypt) and go from there.

最终,HTTPS证书是自签名的,并且您当然不想在本地主机之外使用此证书。 为自己获取CA签名的证书(例如,从LetsEncrypt获得),然后从那里去。

Other than that : happy vertx’ing !

除此之外:祝你快乐!

If you need OAuth based on Google instead of Keycloak, checkout Google OAuth2 with VueJS and Vert.x

如果您需要基于Google的OAuth(而不是Keycloak),请使用VueJS和Vert.x签出Google OAuth2

翻译自: https://www.freecodecamp.org/news/vert-x-vuejs-oauth2-in-5-steps-c04ee78475b7/

vert.x和koa

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值