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(6)

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

Leave a reply

Will not be displayed in comment box .

Loading...