"""Offline ASP.NET MVC security & account models verification lab for Chapter 34 (mvc-security)."""
import hashlib
import hmac
import json
import re
VERSION = "CPython 3.12.14 offline ASP.NET MVC security & DataAnnotations verifier (IIS/ASP.NET host absent)"
def validate_register_model(data):
errors = []
if not data.get("UserName", "").strip():
errors.append("UserName:Required")
email = data.get("Email", "").strip()
if not email:
errors.append("Email:Required")
elif not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
errors.append("Email:EmailAddress")
pwd = data.get("Password", "")
if not pwd:
errors.append("Password:Required")
elif not (6 <= len(pwd) <= 100):
errors.append("Password:StringLength(6..100)")
if data.get("ConfirmPassword", "") != pwd:
errors.append("ConfirmPassword:Compare(Password)")
return errors
def case_account_models_data_annotations_validation():
bad_reg = validate_register_model(
{"UserName": "alice", "Email": "not-an-email", "Password": "123", "ConfirmPassword": "456"}
)
good_reg = validate_register_model(
{"UserName": "alice", "Email": "alice@example.com", "Password": "StrongPassword!1", "ConfirmPassword": "StrongPassword!1"}
)
# ChangePasswordModel check
chg_mismatch = ("oldpwd1" != "") and (len("NewPass1") >= 6) and ("NewPass1" == "WrongConfirm")
expected = {
"bad_register_errors": [
"Email:EmailAddress",
"Password:StringLength(6..100)",
"ConfirmPassword:Compare(Password)",
],
"good_register_valid": True,
"change_password_mismatch_rejected": True,
}
actual = {
"bad_register_errors": bad_reg,
"good_register_valid": len(good_reg) == 0,
"change_password_mismatch_rejected": not chg_mismatch,
}
return {
"name": "account_models_data_annotations_validation",
"summary": "校验 RegisterModel/ChangePasswordModel/LogOnModel 的 Required、StringLength(6..100)、Compare 与邮箱格式验证",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_password_pbkdf2_hashing_and_verify():
salt = b"fixed-offline-test-salt-16b"
dk = hashlib.pbkdf2_hmac("sha256", b"StrongPassword!1", salt, 100000)
verify_ok = hmac.compare_digest(
dk, hashlib.pbkdf2_hmac("sha256", b"StrongPassword!1", salt, 100000)
)
verify_bad = hmac.compare_digest(
dk, hashlib.pbkdf2_hmac("sha256", b"WrongPassword!1", salt, 100000)
)
expected = {
"digest_bytes": 32,
"correct_password_verified": True,
"wrong_password_rejected": True,
"plaintext_not_stored": True,
}
actual = {
"digest_bytes": len(dk),
"correct_password_verified": verify_ok,
"wrong_password_rejected": not verify_bad,
"plaintext_not_stored": b"StrongPassword!1" not in dk,
}
return {
"name": "password_pbkdf2_hashing_and_verify",
"summary": "模拟 ASP.NET Identity PBKDF2-HMAC-SHA256 加盐口令哈希与常量时间 compare_digest 校验",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_rbac_authorize_role_check():
def authorize(user, required_roles=None):
if not user or not user.get("authenticated"):
return 401
if required_roles and not (set(user.get("roles", [])) & set(required_roles)):
return 403
return 200
anon = None
member = {"authenticated": True, "roles": ["Member"]}
admin = {"authenticated": True, "roles": ["Admin", "Member"]}
expected = {"anon_to_admin": 401, "member_to_admin": 403, "admin_to_admin": 200}
actual = {
"anon_to_admin": authorize(anon, ["Admin"]),
"member_to_admin": authorize(member, ["Admin"]),
"admin_to_admin": authorize(admin, ["Admin"]),
}
return {
"name": "rbac_authorize_role_check",
"summary": "模拟 [Authorize(Roles = 'Admin')] 鉴权过滤器对匿名(401)、普通成员(403)与管理员(200)的访问控制",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_csrf_antiforgery_token_verification():
secret = b"offline-antiforgery-key"
session_id = "sess-2026-demo"
cookie_token = hmac.new(secret, session_id.encode(), hashlib.sha256).hexdigest()
def validate_antiforgery(cookie_tok, form_tok):
return bool(cookie_tok and form_tok) and hmac.compare_digest(cookie_tok, form_tok)
expected = {
"matching_token_accepted": True,
"missing_form_token_rejected": True,
"forged_form_token_rejected": True,
}
actual = {
"matching_token_accepted": validate_antiforgery(cookie_token, cookie_token),
"missing_form_token_rejected": not validate_antiforgery(cookie_token, ""),
"forged_form_token_rejected": not validate_antiforgery(cookie_token, "0" * 64),
}
return {
"name": "csrf_antiforgery_token_verification",
"summary": "模拟 @Html.AntiForgeryToken() 与 [ValidateAntiForgeryToken] 的双令牌 HMAC 比对防 CSRF 机制",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_account_models_data_annotations_validation(),
case_password_pbkdf2_hashing_and_verify(),
case_rbac_authorize_role_check(),
case_csrf_antiforgery_token_verification(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。
入口文件:projects/web-pages-mvc-security-lab/explore-mvc-security.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-mvc-security.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a3037.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3047.zip