将keycloak.protect()与express.Router()一起使用 [英] Use keycloak.protect() with express.Router()

查看:266
本文介绍了将keycloak.protect()与express.Router()一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Keycloak保护我的路线,Keycloak是一种开放源代码身份和访问管理. 我试图遵循他们的文档,但无法使其正常工作.

I want to secure my routes using Keycloak which is an open source identity and access management. I have tried to follow their documentation but I was not able to make it work.

这是我的app.js文件:

Here is my app.js file:

const express = require( 'express' );
const routePlaces = require( './routes/placesRoutes' );

const Keycloak = require( 'keycloak-connect' );
const session = require( 'express-session' );
const memoryStrore = new session.MemoryStore();

let kcConfig = {
    clientId =      'parking-app',
    bearerOnly:     true,
    serverUrl:      'localhost:8080/auth',
    realm:          'FlexParking',
    reamlPublicKey: 'MIIBIjANBg…'
}

var keycloak = new KeyCloak( {store: memoryStore}, kcConfig );

app.use( keycloak.middleware({
    //  here I think I have to place my routes
}));

app.use( '/places, routePlaces );
module.exports = app;

服务器是在server.js文件中创建的,并且在尝试使用Keycloak之前,所有端点都可以正常工作.

The server is created in a server.js file and all the endpoints are working perfectly before trying to use Keycloak.

这是我的routePlaces.js文件:

'use strict';
const express = require( 'express' );
const place = require( '../controllers/placesController' );

router.route( '/gps' ).get( place.get_place_by_gps );
router.route( '/street' ).get( place.get_place_by_street );

module.exports = router;

这是我的placesController.js:

'use strict';

exports.get_place_by_gps = ( req, res, next ) => {
    res.send( ' GET places by the GPS position' );
}

exports.get_place_by_street = ( req, res, next ) => {
    res.send( ' GET places by the street name' );
}

我希望使用keycloak.connect('...')保护我的路线('/places/gps'),而使用路线'/places/street'而没有任何保护.如何配置Keycloak中间件来做到这一点?

I want my route ('/places/gps') to be protected using keycloak.connect('...') and the route '/places/street' to be used without any protection. How to configure the Keycloak middleware to do that?

app.use( keycloak.middleware({
    //  here i think i have to place my routes
}));

如何像这样保护路线

router.route( '/gps' ).get( place.get_place_by_gps, keycloak.connect('user'));

推荐答案

> app.use(keycloak.middleware({
> 
> //  here i think i have to place my routes
> 
> }));

不正确.您必须在其中传递options.

It is incorrect. You have to pass the options there.

    app.use(keycloak.middleware({
        logout: logoutUrl,
        admin: '/'
    }));

我要保护的路线必须是

How has to be my route that i want to protect:

router.route('/gps').get(place.get_place_by_gps,keycloak.connect('user'); 上面的东西?

router.route('/gps').get(place.get_place_by_gps,keycloak.connect('user'); something as above?

keycloak.middleware()

本身不做任何保护.它只是尝试从请求中获取grant数据并将其放入特殊对象request.kauth.grant中. 它还做一些其他事情,例如检查注销请求.

Doesn't do any protection itself. It just tries to get grant data from the request and put it in the special object request.kauth.grant. Also it does some additional things, like check for logout request.

要保护资源,您需要添加keycloak.protect()

To protect a resource you need to add keycloak.protect()

 app.get('/gps', keycloak.protect(), handler);

要不保护资源,就不要添加任何内容

To not protect a resource just don't add anything

 app.get('/street', handler);

这是来自 keycloak-nodejs-example 的更复杂的示例, 它使用了自定义的中间件

This is a more complex example from keycloak-nodejs-example, it uses a custom middleware

middleware(logoutUrl) {
        // Return the Keycloak middleware.
        //
        // Specifies that the user-accessible application URL to
        // logout should be mounted at /logout
        //
        // Specifies that Keycloak console callbacks should target the
        // root URL.  Various permutations, such as /k_logout will ultimately
        // be appended to the admin URL.
        let result = this.keyCloak.middleware({
            logout: logoutUrl,
            admin: '/'
        });
        result.push(this.createSecurityMiddleware());
        return result;
    }


    createSecurityMiddleware() {
        return (req, res, next) => {
            if (this.permissions.isNotProtectedUrl(req)) {
                return next();
            }

            const permission = this.permissions.findPermission(req);
            if (!permission) {
                console.log('Can not find a permission for: %s %s', req.method, req.originalUrl);
                return this.keyCloak.accessDenied(req, res);
            }

            this.protectAndCheckPermission(req, res, next, permission.resource, permission.scope);
        };
    }


app.use(keyCloak.middleware('/logout'));

来源

https://github .com/v-ladynev/keycloak-nodejs-example/blob/master/lib/keyCloakService.js#L69

https://github.com /v-ladynev/keycloak-nodejs-example/blob/master/app.js#L60

此外,您还可以在 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆