The WebSecurity Helper
The WebSecurity helper class provides membership functionality out of the box, storing user accounts in a database configured via WebSecurity.InitializeDatabaseConnection, typically called once in _AppStart.cshtml with the account table name, user id column, and username column specified explicitly. WebSecurity.CreateUserAndAccount(username, password) hashes the password and creates both the membership record and an optional profile row in one call, while WebSecurity.Login(username, password) verifies credentials and issues the authentication cookie that keeps a visitor signed in across subsequent requests without re-entering credentials on every page.
Cricket analogy: A cricket board registering a new player's official ID card, complete with verified documents, before they're allowed onto the national team mirrors WebSecurity.CreateUserAndAccount creating a verified membership record with a hashed password.
Authorizing Access to Pages
Guarding a page requires checking WebSecurity.IsAuthenticated before rendering sensitive content, or applying it at the top of a protected page with a pattern like if (!WebSecurity.IsAuthenticated) { Response.Redirect("~/Account/Login"); }, since Web Pages has no built-in [Authorize] attribute the way MVC does. Because every protected page must repeat this check, many Web Pages sites factor the logic into a shared helper file included near the top of each restricted page, or rely on a folder-level _PageStart.cshtml that runs before every page in that directory and can redirect unauthenticated visitors before the page body executes.
Cricket analogy: A stadium gate steward checking every single spectator's ticket individually at each entrance, since there's no automated turnstile system, mirrors WebSecurity.IsAuthenticated being manually checked at the top of every protected page.
Roles and Permissions
Beyond simple authentication, the SimpleRoleProvider adds authorization by grouping users into named roles; Roles.AddUsersToRole(username, "Admin") assigns a role, and a page checks membership with WebSecurity.IsUserInRole("Admin") before exposing administrative functionality like deleting other users' content. Because these role checks are ordinary C# conditionals rather than declarative attributes, a developer must remember to add the check to every relevant page and every relevant action within that page, including AJAX-style handlers that might otherwise be reachable without going through the page's main rendering path.
Cricket analogy: A team's captaincy role granted to only one player, who alone can make certain field-placement decisions, is like Roles.AddUsersToRole assigning an "Admin" role that unlocks specific privileged actions.
Preventing XSS and CSRF
Razor's @variable output is HTML-encoded by default, so displaying user-submitted text like a comment automatically neutralizes embedded <script> tags, closing off the most common cross-site scripting vector without extra effort; explicitly opting out with @Html.Raw() should be reserved for content the developer trusts completely. Cross-site request forgery is addressed with @AntiForgeryToken() emitted inside a form and validated on post with AntiForgery.Validate(), which confirms the submission actually originated from the site's own rendered form rather than from a malicious page that tricked a logged-in user's browser into submitting a hidden request.
Cricket analogy: A stadium's official scorer only accepting a scorecard update if it's stamped with that match's unique official seal, rejecting any unstamped submission, mirrors AntiForgeryToken confirming a form truly originated from the site.
@{
// in _AppStart.cshtml
WebSecurity.InitializeDatabaseConnection(
"StarterSite", "UserProfile", "UserId", "Email", autoCreateTables: true);
}
@{
// login.cshtml
var message = "";
if (IsPost) {
var email = Request["Email"];
var password = Request["Password"];
if (WebSecurity.Login(email, password, persistCookie: true)) {
Response.Redirect("~/Account/Dashboard");
} else {
message = "Invalid email or password.";
}
}
}
@{
// Dashboard.cshtml
if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/Account/Login");
}
if (!WebSecurity.IsUserInRole("Admin")) {
Response.Redirect("~/Account/AccessDenied");
}
}WebSecurity.CreateUserAndAccount hashes and salts passwords automatically; a developer never stores or compares plaintext passwords directly, which removes an entire class of common credential-storage mistakes.
- WebSecurity.InitializeDatabaseConnection configures membership storage, typically once in _AppStart.cshtml.
- WebSecurity.CreateUserAndAccount hashes passwords and creates the account record in one call.
- WebSecurity.Login verifies credentials and issues a persistent authentication cookie.
- Web Pages has no [Authorize] attribute; every protected page must explicitly check WebSecurity.IsAuthenticated.
- SimpleRoleProvider and Roles.AddUsersToRole enable role-based checks via WebSecurity.IsUserInRole.
- Razor auto-encodes @variable output, closing off the most common XSS vector by default.
- @AntiForgeryToken() plus AntiForgery.Validate() protects forms against cross-site request forgery.
Practice what you learned
1. What does WebSecurity.CreateUserAndAccount do?
2. Since Web Pages has no [Authorize] attribute, how is a page typically protected?
3. How does Razor prevent basic cross-site scripting from user-submitted text by default?
4. What does @AntiForgeryToken() combined with AntiForgery.Validate() protect against?
5. Which method checks whether the current user belongs to a specific role like "Admin"?
Was this page helpful?
You May Also Like
Forms and Validation in Web Pages
Learn how ASP.NET Web Pages reads posted form data and enforces validation rules using the Validation helper, from server checks to optional client-side hints.
Database Access in Web Pages
Learn how the WebMatrix.Data.Database helper connects ASP.NET Web Pages to SQL databases with lightweight Query, Execute, and parameterized SQL methods.
Deploying Web Pages Sites
Understand how to publish an ASP.NET Web Pages site to production using FTP or Web Deploy, configure web.config for release, and set correct IIS and App_Data permissions.
Related Reading
Related Study Notes in Microsoft Technologies
Browse all study notesWindows 10 / UWP Development Study Notes
.NET · 30 topics
Microsoft TechnologiesWindows Batch Scripting Study Notes
Batch · 30 topics
Microsoft TechnologiesMFC (Microsoft Foundation Classes) Study Notes
C++ · 30 topics
Microsoft TechnologiesSilverlight Study Notes
.NET · 30 topics
Microsoft TechnologiesXAML Study Notes
.NET · 30 topics
Microsoft TechnologiesWPF (Windows Presentation Foundation) Study Notes
.NET · 30 topics