[keycloak-user] Authenticate a rest api using keycloak access token (received from Authorization header in the HTTP GET request from the front end) in node js

Saransh Kumar skm.8896 at gmail.com
Thu Feb 23 09:39:16 EST 2017


down votefavorite
<http://stackoverflow.com/questions/42394475/authenticate-a-rest-api-using-keycloak-access-token-received-from-authorization#>

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.


More information about the keycloak-user mailing list