静态的RESTify Web服务器停止工作后,启用HTTP基本身份验证 [英] Restify static webserver stops working after enabling HTTP basic authentication

查看:210
本文介绍了静态的RESTify Web服务器停止工作后,启用HTTP基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作的Node.js配置为静态Web服务器工作的RESTify服务器。下面是相关code;

I have a working node.js restify server configured to work as a static webserver. Here is the relevant code;

var server = restify.createServer({
    name: 'myapp',
    version: '1.0.0'
});

var static_webserver = function (app) {
    app.get(/.*/, restify.serveStatic({
        'directory': 'static', //static html files stored in ../static folder
        'default': 'index.html'
    }));
} //var static_server = function (app)

static_webserver(server);

我启用HTTP基本身份验证后,有其他的REST API的更好的安全性,静态Web服务器停止工作。

After I enable HTTP Basic authentication to have better security for the other REST APIs, the static webserver stopped working.

这是code启用HTTP基本身份验证。

This is the code for enabling HTTP Basic authentication.

server.use(restify.authorizationParser());
function verifyAuthorizedUser(req, res, next)
{
    var users;

    users = {
        foo: {
            id: 1,
            password: 'bar'
        }
    };

    if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
        // Respond with { code: 'NotAuthorized', message: '' }
        next(new restify.NotAuthorizedError());
    } else {
        next();
    }

    next();
}//function verifyAuthorizedUser(req, res, next)

server.use(verifyAuthorizedUser);

看来,启用身份验证后,没有网页浏览器能够因为需要验证访问静态HTML网页。我怎样才能为静态Web服务器禁用身份验证,但启用了其他的REST API的认证?

It seems that after enabling authentication, no web browser was able to visit the static html webpages because authentication is required. How can I disable authentication for the static webserver but enable authentication for the other REST APIs?

推荐答案

如果您是的NodeJS最新足以支持<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\"相对=nofollow> string.startsWith()

If your nodejs is up to date enough to support string.startsWith():

function verifyAuthorizedUser(req, res, next) {
    var path = req.path();
    // check if the path starts with /static/
    if (path.startsWith('/static/')) {
        return next();
    }

    var users;
    users = {
        foo: {
            id: 1,
            password: 'bar'
        }
    };

    if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
        // Respond with { code: 'NotAuthorized', message: '' }
        next(new restify.NotAuthorizedError());
    } else {
        next();
    }

    next();
}

如果您还没有startsWith(),一个很好的旧正则表达式会做什么:

If you don't have startsWith(), a good old regex will do:

if (path.match(/\/static\/.*/)) {
    return next();
}

这篇关于静态的RESTify Web服务器停止工作后,启用HTTP基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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