首页 > 解决方案 > 私有 next.js 站点上的简单密码保护

问题描述

我正在制作一个 next.js 应用程序,我花了几个小时寻找一种非常简单的密码保护应用程序的方法。(会被一小群朋友使用)

我已经尝试在我的反向代理上使用 Nginx 的 http auth,这很有效,但是由于登录不会持续很长时间,因此必须一直登录可能会很烦人。(Nginx 的 http auth 好像很快就‘注销’或者忘记授权了)

我也不想深入研究像NextAuth这样复杂的东西。我不希望用户注册、自定义视图等。

我只希望人们能够输入一个密码来查看该网站。而且我希望它在他们的浏览器上持续存在,这样他们就不必一直使用 Nginx 的 http auth 登录。

有没有办法在用户通过 http 身份验证后给他们一个 cookie,然后在他们拥有 cookie 后允许他们进入?

谁能提出一个相当简单的解决方案?提前致谢。

标签: reactjsexpressnginxnextjs

解决方案


你可以使用 Nginxmap指令来做到这一点,它允许你根据另一个变量设置一个变量。

在您的 html 块内某处但在您设置地图指令的任何服务器块之外

map $cookie_trustedclient $mysite_authentication {
  default  "Your credentials please";
  secret-cookie-value off;
}

这里发生的事情是 Nginx 正在$mysite_authentication根据名为的 cookie 的值设置自定义变量的值trustedclient

默认情况下$mysite_authentication将设置为Your credentials please,除非您有一个名为 的 cookie trustedclientsecret-cookie-value在这种情况下$mysite_authentication将设置为off

现在,在您启用基本身份验证的位置块中,您可以更改auth_basic指令以使用新变量,如下所示:

location /secretfiles {
    auth_basic $mysite_authentication;
    auth_basic_user_file .... 
    add_header Set-Cookie "trustedclient=secret-cookie-value;max-age=3153600000;path=/";
}

您可以在此处或在您的网站代码中设置 cookie。结果是该auth_basic指令被设置off为具有正确 cookie 的人,或者为没有它的人设置密码框的显示消息。

不是超级安全,但对于大多数事情来说足够简单且足够好。

从您的配置编辑:

# Map block can go here
map $cookie_trustedclient $mysite_authentication {
  default  "Your credentials please";
  secret-cookie-value off;
}

server {
        listen 443 ssl default_server;
        listen [::]:443 ssl default_server;
 #       ssl     on; # Delete this line, obsolete directive
        ssl_certificate /etc/nginx/cloudflare-ssl/certificate.pem;
        ssl_certificate_key     /etc/nginx/cloudflare-ssl/key.key;

        ssl_client_certificate        /etc/nginx/cloudflare-ssl/cloudflare.crt;
        ssl_verify_client on;

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name ********.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
             #   auth_basic "Restricted Content"; # Now this becomes:
                auth_basic $mysite_authentication;
                auth_basic_user_file /etc/nginx/.htpasswd;
                add_header Set-Cookie "trustedclient=secret-cookie-value;max-age=3153600000;path=/";
        }
}

推荐阅读