【问题标题】:Is there an easy way to protect all endpoints?有没有一种简单的方法来保护所有端点?
【发布时间】:2022-01-15 02:18:19
【问题描述】:

我的 SvelteKit 应用中有大量端点需要保护。我不想在所有这些中添加以下内容:

    if (!request.locals.user) {
        return { status: 401 };
    };

我可以通过hooks.js 或其他简单安全的方式执行此操作吗?

【问题讨论】:

    标签: sveltekit


    【解决方案1】:

    目前没有办法在 sveltekit 中为每个端点添加钩子,并且在全局 hooks.js 中实现它会很困难,因为每次更改时都必须维护受保护的路由路径。

    按照您所说的唯一方法是在每条路由中添加身份验证检查,这也将难以维护。为了避免这种情况,我们可以将身份验证检查逻辑提取到它自己的函数中。该函数将接受持有路由挂钩的处理程序:

    // compose one handler function out of number of handlers.
    // it will execute handlers in sequence until one returned a value
    function withHandlers(...handlers) {
        return async (request) => {
            for (const handle of handlers) {
                const result = await handle(request)
                if (result !== undefined) {
                    return result
                }
            }
        }
    }
    
    // implementation of auth check
    function authHook(request) {
        if (!request.locals.user) {
            return {
                status: 401,
                body: {
                    message: 'unauthorized'
                }
            };
        }
    }
    
    // create a new handler with auth check
    function withAuth(handle) {
        return withHandlers(authHook, handle);
    }
    
    // your final endpoint with authentication check
    export const get = withAuth((request) => {
        return {
            body: `Hello ${request.locals.user}`
        };
    });
    

    【讨论】:

    • 我不得不整理一下,但现在我准备尝试你的答案......我有点愚蠢......你介意将你的代码示例与每个文件的示例分开吗hooks.js, index.js?
    猜你喜欢
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2012-06-15
    • 2020-10-18
    相关资源
    最近更新 更多