keycloak api_使用Keycloak保护NestJS API

keycloak api

From the Keycloak website, “Keycloak is an open source identity and access management solution”. Today we’ll look at how to protect your HTTP API with Keycloak.

在Keycloak网站上,“ Keycloak是一种开源身份和访问管理解决方案”。 今天,我们将研究如何使用Keycloak保护您的HTTP API。

One of the modern ways to protect an HTTP API today is via the “Authorization: Bearer <token>” HTTP header and with the token being a JWT carrying the identity and the claims (roles, etc.) of the consumer of the API.

今天,保护HTTP API的一种现代方法是通过“授权:承载<令牌>” HTTP标头,并且令牌是一个JWT,它带有API使用者的身份和声明(角色等)。

We’ll assume you already have a JS frontend app or at least a HTTP client that performed the authentication against Keycloak and is in possession of a JWT and can pass it as a HTTP “Authorization: Bearer <token>” header to your NestJS backend.

我们假设您已经有一个JS前端应用程序或至少一个对Keycloak执行身份验证并拥有JWT的HTTP客户端,并且可以将其作为HTTP“ Authorization:Bearer <token>”标头传递给NestJS后端。

JWTs can be symmetrically signed (same secret to sign and to verify the JWT) or asymmetrically (token signed with private key and verifiable with the corresponding public key). Keycloak uses the later which is great because it allows multiple backends to be able to verify JWTs without disseminating a secret across multiple services. It means that if one of your service is compromised, at least an attacker won’t be able to forge JWTs on its own to attack other services.

JWT可以对称签名(签名和验证JWT的秘密相同),也可以不对称(使用私钥签名的令牌,并可以使用相应的公钥验证)。 Keycloak使用了后者,这是很好的选择,因为它允许多个后端能够验证JWT,而无需在多个服务之间传播秘密。 这意味着,如果您的一项服务遭到破坏,至少攻击者将无法伪造JWT来攻击其他服务。

实作 (Implementation)

We need to write a Guard that will decorate the controllers or the individual handlers that we want to protect.

我们需要编写一个Guard,它将装饰我们要保护的控制器或单个处理程序。

This guard will use an AuthenticationService which will perform (in various ways as you’ll see below) the verification of the JWT.

该防护将使用AuthenticationService ,它将执行JWT验证 (以各种方式,如下所示)。

All the required services will be part of an AuthenticationModule that will export some of them that may be required by the rest of your application.

所有必需的服务将成为AuthenticationModule的一部分,该身份验证模块将导出应用程序其余部分可能需要的其中一些服务。

We’ll provide a working implementation and refine it later to make it more practical to use in production, in E2E tests, etc.

我们将提供一个可行的实施方案,并在以后对其进行完善,使其在生产,端到端测试等方面更加实用。

Let’s go:

我们走吧:

import { Module } from '@nestjs/common
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值