Redirect to Login when Unauthorized using ASP.NET Core Policy-Based Authorization

Restrict access to Controller using the Authorize attribute (Policy-Based Authorization) and redirect to login

September 6, 2020

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<IAuthorizationHandlerLoggedIn>();
            //ADD AUTHORIZATION POLICY END
        }

        public void Configure(IApplicationBuilder appIWebHostEnvironment 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 (ctxnext) =>
            {
                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)

RileyvewOctober 7, 2024

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

DEUS88January 22, 2025

DEUS88

DEUS88January 29, 2025

DEUS88

JUDI BOLAFebruary 4, 2025

JUDI BOLA

DEUS88February 5, 2025

DEUS88

DEUS88February 12, 2025

DEUS88

SCATTER HITAMApril 21, 2025

SCATTER HITAM

CartertitMay 2, 2025

?????? ??????? ? ?????????? ???????! ???????? ? ????, ????????????? ????????. ?????????, ??????????, ?? ???????? ????. ???????? ??????! ?????????? ? https://uborka-kvartir24top.ru - ??????????? ?????? ?????

RusselljogMay 5, 2025

??????? https://himchistka-divanov-spb24.ru - ????????? ?????? ??? ????????

RobertjefMay 6, 2025

?????????? ? https://himchistka-divanov-msk24.ru - ????????? ??????? ??????

JosephOvabeMay 7, 2025

???????? https://himchistka-msk24.ru

DavidlawMay 7, 2025

???????? https://himchistka-spb24.ru

AntonlannyMay 8, 2025

?????? ????? ? ??? ? ??! ??????? ??????????? ?????? ??? ?????? ????????. ????????? ???????? ? ???????. ?? ????????????! ?????????? ? https://uborka-domov24spb.ru

ThomasfupMay 9, 2025

????? ? ??????? ? ??????? ? ???! ?????????? ???? - ????? ? ?????! ???????????????? ???????. ??????????????? ????. ???????! ????? https://uborka-ofisov24spb.ru

JimmytiemoMay 9, 2025

?????? ????? ???????? ???????? ? ???????????? ????! ???????????????? ?????? ??????? ? ?????. ??????????, ???????????, ???????! ?????????? https://klining-posle-remonta24spb.ru/

JamesfarMay 11, 2025

???????? https://uberu21.ru - ????????? ??????????? ????? ? ???

CarlosVexMay 11, 2025

?????????? ? https://clean-help24.ru/

mob.genmens.ruMay 12, 2025

? ???????? ???????? https://mob.genmens.ru/ ??????????? ??????? ??????????? ?????????? ??? ????????? ???????? ???????????? ?????.??????? ???????? ?? ????????? ????? ? ?????-?????????? ? ?????? ???????? ? ?????? ??????? ?????? ??????.????????? ????????????? ?????? ??? ?????????? ??????? ??????????????? ??????????? ??????.

NorbertfuhMay 14, 2025

????????? https://uslugi-uborki-spb24.ru - ?????? ??????? ???

LloydTicMay 17, 2025

????? ?? ??????? ??????? ??????? ?? ?????? ???! ????????? ???????, ?????? ??????, ?????? ? ??????. ??????? https://himchistka-divanov-msk24.ru/

DanielsnadsMay 19, 2025

?????? ??????? ? ??????! ????????? ????? ??? ???, ? ?? ?? ??????! ???????????????? ???????. ????????? ?? 1590 ???.. ???????? ??????! ?????????? ? https://uborka-kvartir24top.ru

WallaceGokMay 20, 2025

??????? ? ??????! ??????, ????????, ?????. ???????? ??????? ?? ????????? ?????. ????????? ????? ??? ?????! ???????????? ??????? ?? ??????????! ??????? https://uborka-top24.ru

RobertNerMay 20, 2025

??????? https://uborka-v-spv24pro.ru/

https://sportwetten-ohne-oasis.bet/ Sportwetten ohne OASISMay 26, 2025

https://sportwetten-ohne-oasis.bet/ Sportwetten ohne OASIS

spin mama casinoJune 9, 2025

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

50style.ruJune 10, 2025

https://50style.ru/

Leave a reply

Will not be displayed in comment box .

Loading...