You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Astro框架实现静态密码保护页面:案例研究页加密方案咨询

Astro实现带Cookie存储的静态密码保护页面

问题描述

我正在搭建个人作品集,希望为部分页面(案例研究)设置静态密码(如1234)保护,验证通过后将状态存储在浏览器Cookie中,请问如何使用Astro模板实现该功能?以下是我当前的代码:

Layout.astro:

---
import Basehead from "../components/Basehead.astro";
import { SITE_DESCRIPTION,SITE_TITLE } from '../consts';
const {frontmatter} = Astro.props;
---
<html>
  <head>
        <Basehead title={SITE_TITLE} description={SITE_DESCRIPTION}></Basehead>
    </head>

  <h1>{frontmatter.title}</h1>
  <p>{frontmatter.description}</p>
  <img src={frontmatter.cover} height="200" width="200" alt="" >
  <article>
      <slot /> <!-- Markdown content is injected here -->
  </article>
</html>

Page.mdx:
当frontmatter中password: true时,需提示用户输入密码

---
layout: ../layouts/CaseStudyLayout.astro
title: case study post
description: the description
cover: https://framerusercontent.com/images/D5baHWHk2hVJyc1znehFavwU1I.jpeg
password: true
---

import Video from '../components/Video.astro'
export const title = 'My first MDX post'

## Background

This Markdown file creates a page at `your-domain.com/page-1/`

<Video />

解决方案

1. 修改CaseStudyLayout.astro,加入密码验证逻辑

在布局文件中整合服务端Cookie检查与客户端密码表单功能:

---
import Basehead from "../components/Basehead.astro";
import { SITE_DESCRIPTION, SITE_TITLE } from '../consts';
const { frontmatter } = Astro.props;

// 服务端验证Cookie是否有效
const isAuthenticated = Astro.cookies.get('case_study_auth')?.value === 'valid';
// 判断是否需要显示密码表单
const requirePassword = frontmatter.password && !isAuthenticated;
---
<html>
  <head>
    <Basehead title={SITE_TITLE} description={SITE_DESCRIPTION}></Basehead>
    <style>
      .password-container {
        max-width: 320px;
        margin: 4rem auto;
        padding: 2rem;
        border: 1px solid #eee;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      }
      .password-input {
        width: 100%;
        padding: 0.8rem;
        margin: 1rem 0;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-sizing: border-box;
      }
      .submit-btn {
        width: 100%;
        padding: 0.8rem;
        background-color: #2563eb;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }
      .error-text {
        color: #dc2626;
        text-align: center;
        margin-top: 1rem;
      }
    </style>
  </head>
  <body>
    {!requirePassword ? (
      <>
        <h1>{frontmatter.title}</h1>
        <p>{frontmatter.description}</p>
        <img src={frontmatter.cover} height="200" width="200" alt="" >
        <article>
          <slot />
        </article>
      </>
    ) : (
      <div class="password-container">
        <h2>请输入密码访问内容</h2>
        <input type="password" class="password-input" id="pwdInput" placeholder="输入静态密码" />
        <button class="submit-btn" id="verifyBtn">验证</button>
        <div id="errorMsg" class="error-text"></div>
      </div>
    )}

    <script is:inline>
      if ({requirePassword}) {
        const CORRECT_PWD = '1234'; // 替换为你的静态密码
        const pwdInput = document.getElementById('pwdInput');
        const verifyBtn = document.getElementById('verifyBtn');
        const errorMsg = document.getElementById('errorMsg');

        const handleVerify = () => {
          const input = pwdInput.value.trim();
          if (input === CORRECT_PWD) {
            // 设置Cookie,有效期7天(604800秒)
            document.cookie = 'case_study_auth=valid; max-age=604800; path=/; SameSite=Lax';
            // 刷新页面加载受保护内容
            window.location.reload();
          } else {
            errorMsg.textContent = '密码错误,请重新输入';
            pwdInput.focus();
          }
        };

        verifyBtn.addEventListener('click', handleVerify);
        // 支持回车提交
        pwdInput.addEventListener('keydown', (e) => {
          if (e.key === 'Enter') handleVerify();
        });
      }
    </script>
  </body>
</html>

2. MDX页面配置说明

只需在需要保护的MDX页面frontmatter中添加password: true,即可自动启用密码验证,如你提供的示例所示。

核心逻辑说明

  • 服务端预检查:Astro会在页面渲染前检查Cookie,已验证用户直接加载内容,未验证则显示密码表单
  • Cookie持久化:验证通过后设置Cookie,有效期可通过max-age参数调整,path=/确保全站有效
  • 客户端交互:密码表单仅在需要时渲染,验证通过后刷新页面加载内容
  • 安全提示:静态密码仅适用于非敏感内容,生产环境建议通过环境变量(import.meta.env.PROTECTED_PASSWORD)存储密码,避免硬编码暴露

内容的提问来源于stack exchange,提问作者Dark star

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:23:13