如何为node.js应用程序在keycloak中启用策略强制执行?

时间:2018-12-11 10:22:55

标签: node.js redhat keycloak

我必须将node.js应用程序与keycloak集成在一起。该应用程序是快速的,但是策略没有强制执行,它为所有用户授予访问所有api的权限。 对于/ test api: 只有具有“首席”角色的用户才能访问。我已经在keycloak管理控制台中给出了这些策略,但是这些策略没有体现出来。为什么?

没有“首席”角色的用户也正在访问/ test

app.js:

'use strict';

const Keycloak = require('keycloak-connect');
const express = require('express');
const session = require('express-session');
const expressHbs = require('express-handlebars');
const app = express();
app.engine('hbs', expressHbs({extname:'hbs',
 defaultLayout:'layout.hbs',
 relativeTo: __dirname}));
app.set('view engine', 'hbs');
var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({ store: memoryStore });
app.use(session({
 secret:'thisShouldBeLongAndSecret',
 resave: false,
 saveUninitialized: true,
 store: memoryStore
}));
app.use(keycloak.middleware()); 
app.get('/*', keycloak.protect('user'), function(req, res){
     res.send("User has base permission");
    });

app.get('/test', keycloak.protect(), function(req, res){
     res.send("access granted");
    });
app.get('/',function(req,res){
 res.send("hello world");
});
app.use( keycloak.middleware( { logout: '/'} ));
app.listen(3000, function () {
 console.log('Listening at http://localhost:3000');
});

keycloak.json:

{
  "realm": "nodejs-example",
  "auth-server-url": "http://localhost:8180/auth",
  "ssl-required": "external",
  "resource": "nodejs-connect",
  "credentials": {
    "secret": "451317a2-09a1-48b8-b036-e578051687dd"
  },
  "use-resource-role-mappings": true,
  "confidential-port": 0,
  "policy-enforcer": {
      "enforcement-mode":"PERMISSIVE",

  }
}

2 个答案:

答案 0 :(得分:1)

在json中添加以下行

"verify-token-audience": true


var Keycloak = require('keycloak-connect');
var hogan = require('hogan-express');
var express = require('express');
var session = require('express-session');

const app = express();

var server = app.listen(3000, function () {
      var host = server.address().address;
      var port = server.address().port;
      console.log('Example app listening at http://%s:%s', host, port);
    });

app.set('view engine', 'html');
app.set('views', require('path').join(__dirname, '/view'));
app.engine('html', hogan);

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

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

app.use(keycloak.middleware({
      admin: '/',
      protected: '/protected/resourcea'
    }));
app.get('/leads/assign',keycloak.enforcer(['leads:assign'],{
    claims: function(request){
    return {
        "location":["chennai"]
    }
    }
    } ), function (req, res) {
        res.send("granted");
    });


答案 1 :(得分:0)

您在keycloak.json中将执行模式设置为PERMISSIVE,我认为应该是ENCFORCE。