down votefavorite
<
http://stackoverflow.com/questions/42394475/authenticate-a-rest-api-using...
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(); };
Above is my front end code requesting the REST API and passing the keycloak
token in the authorization header which will be needed for authentication
at the node js server side.
*Now I wanted to know how to secure my Rest Api using Keycloak and
authenticate it on the basis of token received from the front end and tell
whether the authentic user is requesting the rest api resource or not?*
I have created a rest api in node js and used keycloak-connect npm packge.
I have mapped the nodejs middleware with keycloak middleware.
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???
});
I have also included the keycloak.json file in the root folder of my
project.