[keycloak-user] Secure NodeJS API using keycloak - how to authenticate using bearer access type

Deepak Garg deepakgarg.garg at gmail.com
Mon Aug 8 01:03:12 EDT 2016


I have created a rest api in node js and used keycloak-connect npm packge.
I have mapped the nodejs middleware with keycloak middleware and just put
keycloak.Protect() method in side api method.

When the user is not logged in, it shows a login screen and ask for
credential. After login, it shows the result. but I don't want to show a
login screen if user is not already logged in. Instead of that i want to
pass the token and get access based upon that token?

Do i need to do anything in the API code so that it will accept the user
token?

I like to use this api through User interface and set the access type
bearer for this service in the keycloak admin.

see the example:

  var express = require('express');
    var apiRoutes = express.Router();
    var User = require('../models/user');
    var jwt = require('jsonwebtoken');
    var faker = require('faker');
    var session = require('express-session');
    var Keycloak = require('keycloak-connect');
    var hogan = require('hogan-express');



    var memoryStore = new session.MemoryStore();

    var keycloak = new Keycloak({store: memoryStore});

        app.use(session({
            secret: app.get('superSecret'),
            resave: false,
            saveUninitialized: true,
            store: memoryStore
        }));

        app.use(keycloak.middleware({
            logout: '/logout',
            admin: '/'
        }));
 app.get('/api/user',* keycloak.protect()*, function (req, res) {
            res.json({
                name: faker.name.findName(),
                email: faker.internet.email(),
                address: faker.address.streetAddress(),
                bio: faker.lorem.sentence(),
                image: faker.image.avatar()

  });
        });


Keycloak.json:


{
  "realm" : "nodejs-example",
  "realm-public-key" :
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0x
tL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/
UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/
p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",
  "auth-server-url" : "http://xxxx:9090/auth",
  "ssl-required" : "external",
  "resource" : "nodejs-connect",
  "public-client" : true
}

Thanks,
Deepak
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.jboss.org/pipermail/keycloak-user/attachments/20160808/f0c3c234/attachment.html 


More information about the keycloak-user mailing list