Hi ruben,
You need to create custom ActionFilter to Authorize the Action Method.
Refer below example.
AuthenticationFilter
public class AuthenticationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
{
string role = actionExecutingContext.HttpContext.Session.GetString("_RoleName");
if (string.IsNullOrEmpty(role) || role.ToLower() != "admin")
{
// Set the route to redirect.
actionExecutingContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Login",
action = "Index"
}));
}
}
}
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Enable Session.
builder.Services.AddSession();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
// Use Session.
app.UseSession();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Controller
Login
public class LoginController : Controller
{
public IActionResult Index()
{
HttpContext.Session.SetString("_RoleName", "admin");
return View();
}
}
Home
public class HomeController : Controller
{
[AuthenticationFilter]
public IActionResult Index()
{
return View();
}
}
View
Login
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h2>Login page</h2>
<a href="/Home/Index">Go to Home</a>
</body>
</html>
Home
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h2>Home page</h2>
</body>
</html>
Screenshot