Hapi-身份验证-hapi-auth-bearer-token

hapi-auth-bearer-token

承载身份验证需要验证由承载授权头或查询参数传递的令牌。

这个身份验证是官方最通人性的, 因为这个简单,并且写了如何调用,其他的都没有,全靠猜。

先贴代码, 普及下api

const Hapi = require('hapi');
const AuthBearer = require('hapi-auth-bearer-token');
const server = Hapi.server({
    port: 3000,
    routes: {
        cors: {
            origin: ['*'],
        }
    }
});
const init = async () => {
    // --- bearer-access-token身份验证 ---
    await server.register(AuthBearer)
    server.auth.strategy('simple', 'bearer-access-token', {
        /**
         * accessTokenName(默认值:'access_token')-重命名令牌密钥,例如'new_name'将令牌查询参数重命名为/route1?new_name=1234。
         * allowQueryToken(默认值:false)-通过查询参数接受令牌。
         * allowCookieToken(默认值:false)-通过cookie接受令牌。
         * allowMultipleHeaders(默认值:false)-接受多个授权头,例如授权:FD AF6C74D1-BBB2-4171-8EE3-7BE9356EB018;承载12345678。
         * tokenType(默认值:'Bearer')-接受自定义的令牌类型,例如Authorization:Basic 12345678。
         * allowCha.(默认值:false)——允许尝试其他身份验证策略
         * unautherized(默认值:Boom.unauthor.)-当使用签名函数([message]、[.]、[attributes])未授权时调用的函数。更多细节
         */
        allowQueryToken: true, // optional, false by default
        validate: async (request, token, h) => {
            /**
             * request  请求对象
             * token    客户端auth令牌
             * h        响应
             */
            console.log(token)
            const isValid = token === '1234';
            const credentials = { token };
            const artifacts = { test: 'info' };
            return { isValid, credentials, artifacts };
        }
    });
    server.auth.default('simple');
    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, h) {
            return 'welcome';
        }
    });
    // 启动服务
    try {
        await server.start();
    }
    catch (err) {
        console.log(err);
        process.exit(1);
    }
    console.log(`Server running at ${server.info.uri}`)
}
init();

调用

// $.ajax({
    type: 'get',
    url: 'http://127.0.0.1:3000',
    data: {
        access_token: '1234' // 跟上边的accessTokenName对应
    },
    success: function (res) {
        console.log(res)
    }
})

搞定~

猜你喜欢

转载自blog.csdn.net/my_atlassian_yhl/article/details/85005059