15. Filters, Authentication and Good Practice

Filters run code before or after an action, for things like authorization and error handling. The [Authorize] attribute blocks users who are not signed in, and roles or policies can limit access further. Finish your learning with good habits: thin controllers, services for logic, validation on the server, and careful handling of errors and secrets.

Key points

  • [Authorize] protects an action or a whole controller; [AllowAnonymous] opens one action.
  • Use app.UseAuthentication() before app.UseAuthorization() in Program.cs.
  • Keep secrets out of source code; use user secrets or environment variables.
  • Handle errors with a custom error page rather than showing stack traces.
  • Write unit tests for services; they are easy to test thanks to dependency injection.

Example: Protecting actions

Controllers/AdminController.cs
[Authorize]
public class AdminController : Controller
{
    public IActionResult Index() => View();

    [Authorize(Roles = "Admin")]
    public IActionResult Users() => View();

    [AllowAnonymous]
    public IActionResult Help() => View();
}
Show explanation

Any signed-in user can open Index. Only users in the Admin role can open Users. Anyone can open Help.