Webpages Security in ASP
Here's a complete and practical overview of WebPages Security in ASP.NET (Razor Web Pages) — how to secure your site using the built-in tools like WebSecurity, AntiForgery, and proper login/registration flows.
? WebPages Security in ASP.NET Web Pages
ASP.NET Web Pages (Razor) includes built-in support for user authentication, authorization, password hashing, and CSRF protection.
? 1. Enabling Security
Use the WebSecurity helper from the WebMatrix.WebData namespace.
? In _AppStart.cshtml:
@{ if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection( "DefaultConnection", // Connection string name "UserProfile", // Users table name "UserId", // User ID column "UserName", // Username column autoCreateTables: true ); }}? 2. User Registration
@{ var result = ""; if (IsPost) { try { WebSecurity.CreateUserAndAccount(Request["username"], Request["password"]); result = "User created!"; } catch (Exception ex) { result = ex.Message; } }}<form method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="Register" /></form><p>@result</p>? 3. User Login
@{ var message = ""; if (IsPost) { var user = Request["username"]; var pass = Request["password"]; if (WebSecurity.Login(user, pass)) { Response.Redirect("~/Index.cshtml"); } else { message = "Invalid credentials"; } }}<form method="post"> <input name="username" /> <input type="password" name="password" /> <input type="submit" value="Login" /></form><p>@message</p>? 4. User Logout
@{ WebSecurity.Logout(); Response.Redirect("~/Login.cshtml");}? 5. Authorization (Restrict Page Access)
@{ if (!WebSecurity.IsAuthenticated) { Response.Redirect("~/Login.cshtml"); }}You can also check roles (if enabled):
@{ if (!Roles.IsUserInRole("Admin")) { Response.Redirect("~/Unauthorized.cshtml"); }}? 6. CSRF Protection (Anti-Forgery Token)
To protect forms from cross-site request forgery:
In Form:
@AntiForgery.GetHtml()<form method="post"> <input type="text" name="name" /> <input type="submit" /></form>In Code:
@{ AntiForgery.Validate(); // Validates token}? 7. Password Hashing (Manually)
@{ var hash = Crypto.HashPassword("myPassword"); var isValid = Crypto.VerifyHashedPassword(hash, "myPassword");}? Best Practices
| Tip | Description |
|---|---|
| ? Use HTTPS | Always use HTTPS in production |
| ? Validate Inputs | Sanitize and validate all form data |
| ? Use AntiForgery | Prevent CSRF attacks |
| ????? Use Roles | Manage admin/user access separately |
| ? Store Passwords Safely | Always use hashed passwords (Crypto/Identity) |
| ? Never Trust User Input | Even if it looks safe |
Let me know if you want working examples of login systems, profile management, or roles setup in Razor Web Pages!