In this article we will cover how to restrict access to controller using the Authorize attribute (Policy-Based Authorization) and make sure that only authenticated users can execute it. Simple and effective.
Prerequisites:
Understanding of ASP.NET Core 3.1
Let's Start:
The first step Let's create a fresh ASP.NET Core 3.1 project.
AuthorizeController.cs
Create Class at root level named "AuthorizeController.cs" and replace it with below mentioned code.
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
namespace HpBlogs
{
public class AuthorizeLoggedInController : IAuthorizationRequirement
{
public AuthorizeLoggedInController()
{
}
}
public class LoggedIn : AuthorizationHandler<AuthorizeLoggedInController>
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;
public LoggedIn(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
AuthorizeLoggedInController requirement)
{
var UserID = _session.GetString("userID");
if (!string.IsNullOrEmpty(UserID))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
}
Startup.cs
Copy below mentioned code and replace it with the code of Startup.cs file.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace HpBlogs
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
});
services.AddHttpContextAccessor();
services.AddControllersWithViews();
//ADD AUTHORIZATION POLICY START
services.AddAuthorization(options =>
{
options.AddPolicy("LoggedIn", policy =>
policy.Requirements.Add(new AuthorizeLoggedInController()));
});
services.AddSingleton<IAuthorizationHandler, LoggedIn>();
//ADD AUTHORIZATION POLICY END
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error/404");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
//SET REDIRECTION BASED ON AUTHORIZATION POLICY START
app.Use(async (ctx, next) =>
{
var ep = ctx.Features.Get<IEndpointFeature>()?.Endpoint;
var authAttr = ep?.Metadata?.GetMetadata<AuthorizeAttribute>();
if (authAttr != null && authAttr.Policy == "LoggedIn")
{
var authService = ctx.RequestServices.GetRequiredService<IAuthorizationService>();
var result = await authService.AuthorizeAsync(ctx.User, ctx.GetRouteData(), authAttr.Policy);
if (!result.Succeeded)
{
var path = $"/login";
ctx.Response.Redirect(path);
return;
}
}
await next();
});
//SET REDIRECTION BASED ON AUTHORIZATION POLICY END
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Controller
Let's create Controller named "CountryController" and add Created Authorization Policy "LoggedIn" to prevent access from user if not logged in.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace HpBlogs.Controllers
{
[Authorize(Policy = "LoggedIn")]
public class CountryController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
Run the project and access CountryController without login and after login
Note: Set below mentioned Session after successfully login
HttpContext.Session.SetInt32("userID", 1);
Additional Information:
1. Just add [Authorize(Policy = "LoggedIn")] to any controller to restrict access without login
2. We can create Multiple Authorize Policy based on requirement like "AdminUser","SuperAdmin" and restrict access to controller.
Additional References:
1. https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1
Post Comments(26)
Viagra * Cialis * Levitra All the products you are looking seeking are currently at one's disposal as far as something 1+1. 4 more tablets of one of the following services: Viagra * Cialis * Levitra https://pxman.net
DEUS88
DEUS88
JUDI BOLA
DEUS88
DEUS88
SCATTER HITAM
?????? ??????? ? ?????????? ???????! ???????? ? ????, ????????????? ????????. ?????????, ??????????, ?? ???????? ????. ???????? ??????! ?????????? ? https://uborka-kvartir24top.ru - ??????????? ?????? ?????
??????? https://himchistka-divanov-spb24.ru - ????????? ?????? ??? ????????
?????????? ? https://himchistka-divanov-msk24.ru - ????????? ??????? ??????
???????? https://himchistka-msk24.ru
???????? https://himchistka-spb24.ru
?????? ????? ? ??? ? ??! ??????? ??????????? ?????? ??? ?????? ????????. ????????? ???????? ? ???????. ?? ????????????! ?????????? ? https://uborka-domov24spb.ru
????? ? ??????? ? ??????? ? ???! ?????????? ???? - ????? ? ?????! ???????????????? ???????. ??????????????? ????. ???????! ????? https://uborka-ofisov24spb.ru
?????? ????? ???????? ???????? ? ???????????? ????! ???????????????? ?????? ??????? ? ?????. ??????????, ???????????, ???????! ?????????? https://klining-posle-remonta24spb.ru/
???????? https://uberu21.ru - ????????? ??????????? ????? ? ???
?????????? ? https://clean-help24.ru/
? ???????? ???????? https://mob.genmens.ru/ ??????????? ??????? ??????????? ?????????? ??? ????????? ???????? ???????????? ?????.??????? ???????? ?? ????????? ????? ? ?????-?????????? ? ?????? ???????? ? ?????? ??????? ?????? ??????.????????? ????????????? ?????? ??? ?????????? ??????? ??????????????? ??????????? ??????.
????????? https://uslugi-uborki-spb24.ru - ?????? ??????? ???
????? ?? ??????? ??????? ??????? ?? ?????? ???! ????????? ???????, ?????? ??????, ?????? ? ??????. ??????? https://himchistka-divanov-msk24.ru/
?????? ??????? ? ??????! ????????? ????? ??? ???, ? ?? ?? ??????! ???????????????? ???????. ????????? ?? 1590 ???.. ???????? ??????! ?????????? ? https://uborka-kvartir24top.ru
??????? ? ??????! ??????, ????????, ?????. ???????? ??????? ?? ????????? ?????. ????????? ????? ??? ?????! ???????????? ??????? ?? ??????????! ??????? https://uborka-top24.ru
??????? https://uborka-v-spv24pro.ru/
https://sportwetten-ohne-oasis.bet/ Sportwetten ohne OASIS
Digital casinos have reshaped the gaming industry, providing a unique kind of ease and breadth that traditional casinos struggle to rival. Over the past decade, a growing community worldwide have embraced the fun of virtual casinos as a result of its ease of access, exciting features, and progressively larger catalogs of games. One of the main appeals of online casinos is the astounding range of titles available. Whether you prefer spinning traditional reel games, trying out narrative-rich modern slot games, or testing your strategy in strategy-based games like Texas Hold’em, digital casinos offer endless options. Many casinos moreover include interactive dealer games, allowing you to participate with real dealers and co-players, all while taking in the immersive ambiance of a land-based casino from anywhere you want. If you’re just starting with the world of virtual gambling or would like to delve deeper into reliable sites, why not sign up for our growing community? It’s a
https://50style.ru/