在节点 js 中使用 keycloak 访问令牌(从前端的 HTTP GET 请求中的授权 header 接收)验证休息 api
Authenticate a rest api using keycloak access token (received from Authorization header in the HTTP GET request from the front end) in node js
var loadData = function () {
var url = 'http://localhost:3000/users';
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'Bearer ' + keycloak.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
console.log('Success');
} else if (req.status == 403) {
console.log('Forbidden');
}
}
}
req.send();
};
以上是我的前端代码请求 REST API 并在授权 header 中传递 keycloak 令牌,这将需要在节点 js 服务器端进行身份验证。
现在我想知道如何使用 Keycloak 保护我的 Rest Api 并根据从前端收到的令牌对其进行身份验证,并判断真实用户是否在请求 rest api资源与否。
我在 node js 中创建了一个 rest api 并使用了 keycloak-connect npm packge。我已经用 keycloak 中间件映射了 nodejs 中间件。
var express = require('express');
var router = express.Router();
var app = express();
var Keycloak = require('keycloak-connect');
var keycloak =new Keycloak();
app.use( keycloak.middleware( {
logout: '/logout',
admin: '/',
} ));
router.get('/users',function(req, res, next) {
var token=req.headers['authorization']; //Access token received from front end
//Now how to authenticate this token with keycloak???
});
我还在项目的根文件夹中包含了 keycloak.json 文件。
查看keycloak.protect()函数。用它来验证您的路线。
router.get('/users',keycloak.protect(),function(req, res, next) {
});
nodejs 4.0.0.1 beta 中间件似乎需要一个名为 request.kauth 的完整对象,其中包含完整的有效负载。
http://lists.jboss.org/pipermail/keycloak-user/2017-February/009719.html
return function protect (request, response, next) {
if (request.kauth && request.kauth.grant) {* // Line 2*
if (!guard || guard(request.kauth.grant.access_token, request,
response)) {
return next();
}
return keycloak.accessDenied(request, response, next);
}
我不确定编码解码发生在何处或发生了什么。似乎它在文档中丢失了。
查看 ,其中概述了如何通过将令牌(由客户端请求提供)发送到 Keycloak 的用户信息路由来验证令牌(由客户端请求提供)在节点 REST API 中是否有效。
此解决方案建议:
Implementing a function to inspect each request for a bearer token and
send that token off for validation by your Keycloak server at the
userinfo endpoint before it is passed to your api's route handlers.
使用 Node 的代码示例。js/Express:
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);
});
var loadData = function () {
var url = 'http://localhost:3000/users';
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'Bearer ' + keycloak.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
console.log('Success');
} else if (req.status == 403) {
console.log('Forbidden');
}
}
}
req.send();
};
以上是我的前端代码请求 REST API 并在授权 header 中传递 keycloak 令牌,这将需要在节点 js 服务器端进行身份验证。
现在我想知道如何使用 Keycloak 保护我的 Rest Api 并根据从前端收到的令牌对其进行身份验证,并判断真实用户是否在请求 rest api资源与否。
我在 node js 中创建了一个 rest api 并使用了 keycloak-connect npm packge。我已经用 keycloak 中间件映射了 nodejs 中间件。
var express = require('express');
var router = express.Router();
var app = express();
var Keycloak = require('keycloak-connect');
var keycloak =new Keycloak();
app.use( keycloak.middleware( {
logout: '/logout',
admin: '/',
} ));
router.get('/users',function(req, res, next) {
var token=req.headers['authorization']; //Access token received from front end
//Now how to authenticate this token with keycloak???
});
我还在项目的根文件夹中包含了 keycloak.json 文件。
查看keycloak.protect()函数。用它来验证您的路线。
router.get('/users',keycloak.protect(),function(req, res, next) {
});
nodejs 4.0.0.1 beta 中间件似乎需要一个名为 request.kauth 的完整对象,其中包含完整的有效负载。
http://lists.jboss.org/pipermail/keycloak-user/2017-February/009719.html
return function protect (request, response, next) {
if (request.kauth && request.kauth.grant) {* // Line 2*
if (!guard || guard(request.kauth.grant.access_token, request,
response)) {
return next();
}
return keycloak.accessDenied(request, response, next);
}
我不确定编码解码发生在何处或发生了什么。似乎它在文档中丢失了。
查看
此解决方案建议:
Implementing a function to inspect each request for a bearer token and send that token off for validation by your Keycloak server at the userinfo endpoint before it is passed to your api's route handlers.
使用 Node 的代码示例。js/Express:
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);
});