简体   繁体   English

使用密钥斗篷在 python API 中验证 JWT 令牌

[英]Validate JWT token in python API with keycloak

I am building a python flask API. The requests are sent from the UI and they include an already authorized JWT token in the header (as expected bearer token).我正在构建一个 python flask API。请求是从 UI 发送的,它们在 header 中包含一个已经授权的 JWT 令牌(如预期的承载令牌)。

My API service needs to validate the token and extract the tenant from the token.我的 API 服务需要验证令牌并从令牌中提取租户。

I have a few questions about how a solution like that usually works.我有几个关于这样的解决方案通常如何运作的问题。

  • does the API just need to decode the token and get the tenant from the payload? API 是否只需要解码令牌并从有效负载中获取租户?
  • the api cannot validate the signature of the token because I don't have the secret, right? api 无法验证令牌的签名,因为我没有秘密,对吗?
  • should the api juat call the auth. api juat 是否应该调用 auth. Server (in thia case key cloak)?服务器(在这种情况下是密钥斗篷)? If yes can someone please write an example code for that.如果是,有人可以为此编写示例代码。 Which libraries are good to use?哪些库很好用?

Thank you谢谢

Here are some answers.这里有一些答案。

  • From a pure technical point of view, you can indeed decode the JWT token (there exists plenty of libs to do it) to extract the payload claims, and you can do it "serverless"从纯技术的角度来看,您确实可以解码 JWT 令牌(有很多库可以做到这一点)以提取有效负载声明,并且可以“无服务器”进行
  • The secret is used to CREATE the signature, not to verify it.秘密用于创建签名,而不是验证它。 When the signature is created (by the keycloak server) using a private key, the client app can verify it using the public key当使用私钥创建签名(由 keycloak 服务器)时,客户端应用程序可以使用公钥对其进行验证
  • Issuing an additional request to the KC server in order to decode the token has yet some added value.向 KC 服务器发出附加请求以解码令牌还有一些附加值。 The (possibly long-living) token may, for some security reason, have been discarded to prevent if from being still used.出于某些安全原因,(可能长期存在的)令牌可能已被丢弃以防止仍在使用。 In such case, the API will return a negative answer.在这种情况下,API 将返回否定答案。 The web service you need to invoke is the "Token Introspection Endpoint" ( https://www.oauth.com/oauth2-servers/token-introspection-endpoint/ )您需要调用的 web 服务是“Token Introspection Endpoint”( https://www.oauth.com/oauth2-servers/token-introspection-endpoint/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM