What is URL-Based Authentication
URL-based authentication means securing specific URLs, folders, or route patterns so only authorized users can access them.
Examples:
/admin only for Admins
/reports/daily only for Managers
/api/* only for logged-in users
1. URL-Based Authentication in ASP.NET Core
1.1 Protect a Folder or Route Pattern
Example: protect all URLs starting with /admin.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "admin",
pattern: "admin/{controller=Dashboard}/{action=Index}/{id?}")
.RequireAuthorization("AdminOnly");
});
Authorization policy:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly",
policy => policy.RequireRole("Admin"));
});
1.2 Protect a Specific URL
app.MapGet("/reports/daily", () => "Daily Report")
.RequireAuthorization("ManagerOnly");
Policy:
options.AddPolicy("ManagerOnly",
policy => policy.RequireRole("Manager"));
});
1.3 Protect Controller Actions
[Authorize(Roles = "Admin")]
public IActionResult Settings()
{
return View();
}
This protects the URL /settings.
1.4 Custom Middleware to Block URLs
app.Use(async (context, next) =>
{
var path = context.Request.Path.Value;
if (path.StartsWith("/secret") && !context.User.Identity.IsAuthenticated)
{
context.Response.Redirect("/account/login");
return;
}
await next();
});
2. URL-Based Authentication in Classic ASP.NET MVC (Non-Core)
2.1 Protect a Folder Using web.config
<location path="Admin">
<system.web>
<authorization>
<deny users="?" />
<allow roles="Admin" />
</authorization>
</system.web>
</location>
2.2 Protect a Single Page
<location path="Reports/Monthly.aspx">
<system.web>
<authorization>
<deny users="?" />
<allow roles="Manager" />
</authorization>
</system.web>
</location>
2.3 Protect Controller URL
[Authorize(Roles = "Admin")]
public ActionResult Dashboard()
{
return View();
}
3. Role-Based URL Control Example
[Authorize(Roles = "Admin, Manager")]
public IActionResult Index()
{
return View();
}
Route level:
endpoints.MapControllerRoute(
name: "report",
pattern: "reports/{*any}")
.RequireAuthorization("ManagerOnly");
4. URL-Based Authentication for Web APIs
[Authorize]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult Get(int id)
{
return Ok();
}
}
Protect all order-related API URLs:
app.MapControllerRoute("api-protected", "api/orders/{*path}")
.RequireAuthorization();
Conclusion
ASP.NET Core provides middleware, routing, and policies for URL-based protection. Classic ASP.NET MVC uses web.config and Authorize attributes.