4

I created a custom Authorization policy in .NET 6 Core. It works fine for my requirement however I found an error while debugging - Session has not been configured for this application or request. But I have already configured the session in my program.cs. Should this error be shown in debugging, Is something remaining to be configured for the session?

Debugging Error Screenshot : https://pasteboard.co/RuiKarjvJPuP.png

Authorization Handler:

using Microsoft.AspNetCore.Authorization;

namespace myApp.Security
{
    public class CrudAccessHandler : AuthorizationHandler<AccessRequirement>
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public CrudAccessHandler(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessRequirement requirement)
        {
            string? controllerName = httpContextAccessor.HttpContext?.Request.RouteValues["controller"]?.ToString();

            string? actionName = httpContextAccessor.HttpContext?.Request.RouteValues["action"]?.ToString();

            if (controllerName != null && actionName != null)
            {
                if (context.User.HasClaim(claim => (claim.Type == controllerName && claim.Value == actionName)))
                {
                    context.Succeed(requirement);
                }
            }

            if (controllerName != null && actionName == "Index")
            {
                if (context.User.HasClaim(claim => (claim.Type == controllerName && claim.Value == "Read")))
                {
                    context.Succeed(requirement);
                }
            }

            if (controllerName != null && actionName == "Clone")
            {
                if (context.User.HasClaim(claim => (claim.Type == controllerName && claim.Value == "Create")))
                {
                    context.Succeed(requirement);
                }
            }

            return Task.CompletedTask;
        }
    }
}

Program.cs:

using myApp.Data;
using MyApp.Interfaces;
using MyApp.Models;
using MyApp.Security;
using MyApp.Services;
using MyApp.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddDbContextPool<ApplicationDbContext>(options => 
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders().AddDefaultUI();
builder.Services.AddTransient<IEmailSender, MailSender>();

builder.Services.Configure<IdentityOptions>(options =>
{
    options.Password.RequiredLength = 8;
});
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
}
);
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Account/Login";
});


builder.Services.AddControllersWithViews(options => 
{ 
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});

builder.Services.Configure<DataProtectionTokenProviderOptions>(options =>
{
    options.TokenLifespan = TimeSpan.FromMinutes(5);
});

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy(Helper.AccessPolicy, policy => policy.AddRequirements(new CrudAccessRequirement()));

    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

builder.Services.AddTransient<IAuthorizationHandler, SuperAdminHandler>();

builder.Services.AddTransient<IAuthorizationHandler, CrudAccessHandler>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

1 Answer 1

13

I resolved my issue by changing the HTTP request pipeline order as follows:

app.UseRouting();
app.UseSession();

app.UseAuthentication();
app.UseAuthorization();

This fixed my issue with .NET 6 Core

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.