大佬教程收集整理的这篇文章主要介绍了node.js – Keycloak:访问令牌验证终点,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
来自keyclaok的jwt令牌正在与每个api调用一起发送.只有在发送的令牌是有效令牌时它才会响应.
>我如何从微服务验证访问令牌?
> keycloak是否有任何令牌验证?
实现一个函数来检查对承载令牌的每个请求,并在将其传递给api的路由处理程序之前,将该令牌发送到userinfo端点的keycloak服务器进行验证.
您可以通过请求其well-known configuration来找到您的keycloak服务器的特定端点(如userinfo路由).
如果您在节点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,next) => { const err = new Error('Not Found'); err.status = 404; next(err); });
向Keycloak的userinfo端点发出请求是验证令牌是否有效的简单方法.
来自有效令牌的Userinfo响应:
{ "sub": "xxx-xxx-xxx-xxx-xxx","name": "John Smith","preferred_username": "jsmith","given_name": "John","family_name": "Smith","email": "john.smith@example.com" }
来自无效有效令牌的Userinfo响应:
{ "error": "invalid_token","error_description": "Token invalid: Token is not active" }
附加信息:
Keycloak提供了自己的名为keycloak-connect的npm包.该文档描述了对路由的简单身份验证,要求用户登录以访问资源:
app.get( '/complain',keycloak.protect(),complaintHandler );
我还没有发现这种方法使用仅承载身份验证.根据我的经验,在路由上实现这种简单的身份验证方法会导致“拒绝访问”响应. This question还询问如何使用Keycloak访问令牌验证rest api. The accepted answer建议使用keycloak-connect提供的简单身份验证方法,但正如Alex在评论中所述:
以上是大佬教程为你收集整理的node.js – Keycloak:访问令牌验证终点全部内容,希望文章能够帮你解决node.js – Keycloak:访问令牌验证终点所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。