Learning Objectives:
- Understand the importance of input validation and learn how to validate user inputs to prevent attacks such as SQL Injection.
- Learn how to use ASP.NET Core Data Protection to securely store and protect sensitive data.
- Understand CORS (Cross-Origin Resource Sharing) and how to configure it to allow your Angular front end to communicate securely with your ASP.NET Core backend.
Input Validation and Data Protection
What is Input Validation? Input validation ensures that user inputs are clean, safe, and valid before processing them. This is crucial to prevent security vulnerabilities like SQL Injection or Cross-Site Scripting (XSS).
How to Implement Input Validation in ASP.NET Core:
- Use Data Annotations in model classes to enforce validation rules, such as
[Required]
or[StringLength]
. - Use FluentValidation or custom validation logic for complex scenarios.
Example: Validating User Input:
public class UserRegistration
{
[Required(ErrorMessage = "Username is required")]
[StringLength(20, MinimumLength = 5, ErrorMessage = "Username must be between 5 and 20 characters")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
- Data Annotations: Enforce basic rules for inputs such as minimum length and required fields.
Real-Life Example: In a user registration system, validating that a username and password meet specific criteria (like length or characters allowed) helps prevent malicious inputs from being processed.
ASP.NET Core Data Protection
ASP.NET Core Data Protection helps in securely storing sensitive information, such as authentication tokens, password reset tokens, or cookies. It encrypts data to prevent unauthorized access.
Example: Protecting Sensitive Data:
Configure Data Protection in Program.cs
:
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"C:\keys"))
.SetApplicationName("MyApp");
Using Data Protection
private readonly IDataProtector _protector;
public UserController(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("UserTokenProtector");
}
[HttpPost("store-token")]
public IActionResult StoreToken(string token)
{
var protectedToken = _protector.Protect(token);
// Store protectedToken safely (e.g., in the database)
return Ok(protectedToken);
}
[HttpGet("get-token")]
public IActionResult GetToken(string protectedToken)
{
var unprotectedToken = _protector.Unprotect(protectedToken);
return Ok(unprotectedToken);
}
- Protect: Encrypts sensitive data.
- Unprotect: Decrypts the data for use when needed.
Real-Life Example: In a financial system, tokens used for password resets or payments should be encrypted before storing them to prevent unauthorized access.
CORS (Cross-Origin Resource Sharing)
What is CORS? CORS (Cross-Origin Resource Sharing) is a security feature implemented in browsers to control how web pages interact with resources from different origins. When you have an Angular front end communicating with an ASP.NET Core API, you need to configure CORS to permit specific interactions while maintaining security.
Why Use CORS?
- To allow your frontend (e.g.,
http://localhost:4200
) to communicate with your backend API (http://localhost:5000
). - To prevent unauthorized domains from accessing your resources.
Configuring CORS in ASP.NET Core:
Add CORS in Program.cs
:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAngularApp",
builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Use CORS Policy in Middleware:
var app = builder.Build();
app.UseCors("AllowAngularApp");
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
Real-Life Example: In an e-commerce application, you might need to allow your Angular front end to access products or user data from the backend API. Configuring CORS ensures that only your specific frontend can interact with your backend services, protecting against unauthorized access from other websites.
Key Takeaways
- Input Validation: Protects the application from malicious inputs. Always validate user inputs to prevent attacks.
- Data Protection: Use ASP.NET Core Data Protection to safely store sensitive information such as tokens or payment information.
- CORS Configuration: Allows the frontend application to interact with the backend securely. Configure CORS policies to permit only authorized frontends.
Practical Questions
- Why is input validation crucial for application security?
- How would you protect sensitive data like tokens in an ASP.NET Core application?
- What is CORS, and why is it important when building applications with a separate frontend and backend?
New Concepts in .NET 8
New in .NET 8:
- Enhanced CORS Middleware: .NET 8 has streamlined CORS configuration and error messages to improve debugging when requests are blocked.
- Data Protection Improvements: The data protection system has new support for native AOT, which improves performance, especially when encrypting/decrypting data.