reactjs - 私有 next.js 站点上的简单密码保护
问题描述
我正在制作一个 next.js 应用程序,我花了几个小时寻找一种非常简单的密码保护应用程序的方法。(会被一小群朋友使用)
我已经尝试在我的反向代理上使用 Nginx 的 http auth,这很有效,但是由于登录不会持续很长时间,因此必须一直登录可能会很烦人。(Nginx 的 http auth 好像很快就‘注销’或者忘记授权了)
我也不想深入研究像NextAuth这样复杂的东西。我不希望用户注册、自定义视图等。
我只希望人们能够输入一个密码来查看该网站。而且我希望它在他们的浏览器上持续存在,这样他们就不必一直使用 Nginx 的 http auth 登录。
有没有办法在用户通过 http 身份验证后给他们一个 cookie,然后在他们拥有 cookie 后允许他们进入?
谁能提出一个相当简单的解决方案?提前致谢。
解决方案
你可以使用 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 trustedclient
,secret-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=/";
}
}
推荐阅读
- laravel - Laravel 7.x Observer 未保存,created_by updated_by 用户
- c# - 初始化对象在 OnAwake 和 OnEnable() 之间变为空
- pandas - 将熊猫隐藏到列表中
- android - 按下按钮后改变其外观?
- ruby - 有没有办法用水晶语言做单线?
- javascript - 错误:参数“数据”的值不是有效的 Firestore 文档。不能使用“未定义”;作为 Firestore 值
- reactjs - Netlify-forms 联系表单提交 404 错误
- python - Python - 类方法返回对象。如何读取对象数据?
- reactjs - 如何将 Draggable 捕捉到网格?(材质界面)
- amazon-web-services - Postman 上的 AWS 响应超时