Chapter 14: Web Pages Security
Web Pages – WebSecurity Object (or WebPages Security in the menu, specifically focusing on the WebSecurity helper at https://www.w3schools.com/asp/webpages_security.asp).
This is where your website stops being “public playground” and becomes a real, secure application with user accounts, logins, passwords, and protected areas (like admin panels or member-only pages). In Hyderabad terms: think of it as putting a lock and doorbell on your flat — only people with the right key (username + password) can enter certain rooms!
WebSecurity is a built-in helper (from the WebMatrix.WebData namespace) that gives you a complete, simple membership system — no need to write complex authentication code from scratch. It’s part of the Simple Membership provider (very lightweight compared to full ASP.NET Membership).
1. What Does WebSecurity Provide? (The Big Wins)
- User registration (create account with email/username + password)
- Login / Logout
- Password change / reset (with email token)
- Account confirmation (email verification)
- Check if user is logged in (IsAuthenticated)
- Get current user’s name or ID
- Protect pages (redirect or block if not logged in)
- Basic role support (in some extensions, but core is user-level)
It’s database-backed — stores users in two tables:
- UserProfile → UserId, Email (or username)
- webpages_Membership → passwords (hashed!), creation dates, confirmation tokens, etc.
No need to manage sessions or cookies manually — WebSecurity handles the auth cookie for you.
2. Step 1: Mandatory Initialization (Do This First!)
You must initialize WebSecurity once — best place is _AppStart.cshtml in the root (runs automatically on app start).
~/ _AppStart.cshtml
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@{ // This MUST be called before using any WebSecurity method WebSecurity.InitializeDatabaseConnection( connectionStringName: "Users", // Name of connection string OR database name userTableName: "UserProfile", // Table for user info userIdColumn: "UserId", // PK column (int) userNameColumn: "Email", // Login field (usually email) autoCreateTables: true // Create tables if missing ); } |
Important notes (teacher yelling mode):
- Database file (e.g. Users.sdf) must already exist in App_Data folder — WebSecurity won’t create the .sdf file, only tables inside it.
- autoCreateTables: true → creates UserProfile and webpages_Membership automatically (very handy!)
- If using full SQL Server → use connection string name from Web.config
- Add to Web.config (to avoid hosting errors):
|
0 1 2 3 4 5 6 7 8 |
<appSettings> <add key="enableSimpleMembership" value="true"/> </appSettings> |
3. Core Properties (Quick Check – Use These Everywhere!)
| Property | What it returns | Typical usage |
|---|---|---|
| WebSecurity.IsAuthenticated | true if user is logged in | if (!WebSecurity.IsAuthenticated) { Response.Redirect(“~/Login”); } |
| WebSecurity.CurrentUserName | Email/username of logged-in user | <p>Welcome, @WebSecurity.CurrentUserName!</p> |
| WebSecurity.CurrentUserId | Integer UserId | For queries like WHERE UserId = @0 |
| WebSecurity.HasLocalAccount(userId) | true if user has local password (not OAuth) | Advanced |
4. Main Methods – With Real Examples
A. Register a New User
In Register.cshtml
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
@{ var success = false; var error = ""; if (IsPost) { var email = Request["email"]; var password = Request["password"]; var confirm = Request["confirm"]; if (password != confirm) { error = "Passwords don't match!"; } else { try { // Create user – returns UserId if success var userId = WebSecurity.CreateUserAndAccount( email, // username (email here) password, // plain text – gets hashed automatically! new { Email = email } // optional extra profile fields ); success = true; } catch (Exception ex) { error = "Registration failed: " + ex.Message; // e.g. "User already exists" } } } } <h2>Register</h2> @if (success) { <p style="color:green;">Account created! <a href="~/Login">Login now</a></p> } else if (!String.IsNullOrEmpty(error)) { <p style="color:red;">@error</p> } <form method="post"> Email: <input type="email" name="email" required /><br> Password: <input type="password" name="password" required /><br> Confirm: <input type="password" name="confirm" required /><br> <input type="submit" value="Register" /> </form> |
→ CreateUserAndAccount = most common (creates both profile + membership record)
B. Login
In Login.cshtml
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
@{ var error = ""; if (IsPost) { var email = Request["email"]; var password = Request["password"]; var remember = Request["rememberMe"] == "on"; if (WebSecurity.Login(email, password, rememberMe: remember)) { // Success → redirect to original page or home var returnUrl = Request.QueryString["ReturnUrl"]; Response.Redirect(returnUrl ?? "~/"); } else { error = "Invalid email or password."; } } } <h2>Login</h2> @if (!String.IsNullOrEmpty(error)) { <p style="color:red;">@error</p> } <form method="post"> Email: <input type="email" name="email" required /><br> Password: <input type="password" name="password" required /><br> <input type="checkbox" name="rememberMe" /> Remember me<br> <input type="submit" value="Login" /> </form> |
→ WebSecurity.Login(…) sets auth cookie → IsAuthenticated becomes true
C. Logout (Simple!)
In any page (e.g. in layout or logout link):
|
0 1 2 3 4 5 6 7 8 9 |
@{ WebSecurity.Logout(); Response.Redirect("~/"); } |
D. Protect Pages (Require Login)
In any protected page (e.g. Members/Dashboard.cshtml):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
@{ if (!WebSecurity.IsAuthenticated) { Response.Redirect("~/Login?ReturnUrl=" + HttpUtility.UrlEncode(Request.Url.AbsolutePath)); } // Or stricter: WebSecurity.RequireAuthenticatedUser(); // exits page if not logged in } |
→ RequireAuthenticatedUser() / RequireRoles(“Admin”) / RequireUser(“admin@site.com”) — all auto-redirect or halt
E. Change Password
|
0 1 2 3 4 5 6 7 8 9 10 |
var success = WebSecurity.ChangePassword( WebSecurity.CurrentUserName, Request["oldPassword"], Request["newPassword"] ); |
F. Password Reset (Forgot Password Flow)
- Generate token → send via email (combine with WebMail!)
|
0 1 2 3 4 5 6 7 |
var token = WebSecurity.GeneratePasswordResetToken(email, 1440); // expires in 1440 min = 24h // Send email with link: ~/Reset?token=abc123 |
- Reset:
|
0 1 2 3 4 5 6 |
WebSecurity.ResetPassword(Request["token"], Request["newPassword"]); |
5. Quick Comparison Table – Your Cheat Sheet
| Task | Method/Property | Example Call |
|---|---|---|
| Setup | InitializeDatabaseConnection | In _AppStart |
| Register | CreateUserAndAccount | userId = WebSecurity.CreateUserAndAccount(…) |
| Login | Login(username, password, rememberMe) | WebSecurity.Login(email, pwd, true) |
| Logout | Logout() | WebSecurity.Logout() |
| Is logged in? | IsAuthenticated | if (WebSecurity.IsAuthenticated) |
| Current user | CurrentUserName / CurrentUserId | @WebSecurity.CurrentUserName |
| Protect page | RequireAuthenticatedUser() | WebSecurity.RequireAuthenticatedUser() |
| Change password | ChangePassword(userName, old, new) | WebSecurity.ChangePassword(…) |
| Reset password token | GeneratePasswordResetToken(username, minutes) | token = WebSecurity.GeneratePasswordResetToken(…) |
| Reset with token | ResetPassword(token, newPassword) | WebSecurity.ResetPassword(token, newPwd) |
6. Teacher Final Advice (2026 Reality)
- WebSecurity = excellent learning tool — simple, database-first membership
- In production 2026 → most people use ASP.NET Core Identity (more features, OAuth built-in, async, better security defaults)
- But concepts (register → login → protect → logout) are universal
- Always hash passwords (WebSecurity does it automatically!)
- Use HTTPS in production (cookies can be stolen otherwise)
- For email confirmation/reset → combine with WebMail helper (previous lesson)
Questions for next?
- Want full forgot password + email reset flow?
- Add roles (simple way with WebSecurity)?
- Protect folder with _PageStart.cshtml?
- Or next topic: WebPages Publish or end of WP track?
Tell me — you’re almost through the whole W3Schools ASP section like a pro from Hyderabad! Keep rocking! 🚀🇮🇳
