node.js - Keycloak:访问 token 验证端点

标签 node.js keycloak

在独立模式下运行 keycloak。并使用 node.js 适配器创建微服务以验证 api 调用。

来自 keyclaok 的 jwt token 随每个 api 调用一起发送。只有当发送的 token 有效时,它才会响应。

  • 如何验证来自微服务的访问 token ?
  • keycloak 是否提供任何 token 验证?

最佳答案

展开troger19's answer :

Question 1: How can I validate the access token from the micro service?

实现一个函数来检查每个持有者 token 的请求,并在将 token 传递给您的 api 的路由处理程序之前发送该 token 以供您的 keycloak 服务器在 userinfo 端点进行验证。

您可以通过请求其 well-known configuration 来找到您的 keycloak 服务器的特定端点(如 userinfo 路由) .

如果您在 Node api 中使用 expressjs,这可能如下所示:

const express = require("express");
const request = require("request");

const app = express();

/*
 * additional express app config
 * app.use(bodyParser.json());
 * app.use(bodyParser.urlencoded({ extended: false }));
 */

const keycloakHost = 'your keycloak host';
const keycloakPort = 'your keycloak port';
const realmName = 'your keycloak realm';

// check each request for a valid bearer token
app.use((req, res, next) => {
  // assumes bearer token is passed as an authorization header
  if (req.headers.authorization) {
    // configure the request to your keycloak server
    const options = {
      method: 'GET',
      url: `https://${keycloakHost}:${keycloakPort}/auth/realms/${realmName}/protocol/openid-connect/userinfo`,
      headers: {
        // add the token you received to the userinfo request, sent to keycloak
        Authorization: req.headers.authorization,
      },
    };

    // send a request to the userinfo endpoint on keycloak
    request(options, (error, response, body) => {
      if (error) throw new Error(error);

      // if the request status isn't "OK", the token is invalid
      if (response.statusCode !== 200) {
        res.status(401).json({
          error: `unauthorized`,
        });
      }
      // the token is valid pass request onto your next function
      else {
        next();
      }
    });
  } else {
    // there is no token, don't process request further
    res.status(401).json({
    error: `unauthorized`,
  });
});

// configure your other routes
app.use('/some-route', (req, res) => {
  /*
  * api route logic
  */
});


// catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

Question 2: Is there any token validation availed by Keycloak?

向 Keycloak 的 userinfo 端点发出请求是验证您的 token 是否有效的一种简单方法。

来自有效 token 的用户信息响应:

Status: 200 OK

{
    "sub": "xxx-xxx-xxx-xxx-xxx",
    "name": "John Smith",
    "preferred_username": "jsmith",
    "given_name": "John",
    "family_name": "Smith",
    "email": "john.smith@example.com"
}

来自无效 token 的用户信息响应:

Status: 401 Unauthorized

{
    "error": "invalid_token",
    "error_description": "Token invalid: Token is not active"
}

附加信息:

Keycloak 提供了自己的 npm 包,名为 keycloak-connect .该文档描述了路由上的简单例份验证,要求用户登录才能访问资源:

app.get( '/complain', keycloak.protect(), complaintHandler );

我还没有发现这种方法可以使用仅承载身份验证。根据我的经验,在路由上实现这种简单的身份验证方法会导致“拒绝访问”响应。 This question还询问如何使用 Keycloak 访问 token 对 rest api 进行身份验证。 The accepted answer建议也使用 keycloak-connect 提供的简单例份验证方法,但正如 Alex 在评论中所述:

"The keyloak.protect() function (doesn't) get the bearer token from the header. I'm still searching for this solution to do bearer only authentication – alex Nov 2 '17 at 14:02

关于node.js - Keycloak:访问 token 验证端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48274251/

相关文章:

javascript - 如何知道 node-webkit 应用程序是否以管理员/提升权限运行?

java - Wildfly 服务器在非 Windows 环境中失败并出现错误 WFLYCTL0017 && WFLYCTL0013

node.js - Node+Express+NGINX 应用程序返回 localhost 而不是域

javascript - 解析单个用户输入字符串以获取高级搜索条件

Keycloak REST API 403 禁止

single-sign-on - 如何使用 SAML ECP 配置文件配置 Keycloak

nginx - 在 Keycloak 中从上游读取响应 header 时,上游发送的 header 太大

java - 从 KeyCloak 导出所有用户

javascript - Node js 显示来自服务器的图像

css - 在 node.js 应用程序中切换 CSS 主题