Rahul Aggarwal
Rahul Aggarwal

Reputation: 291

User not getting redirected to unauthorized page when not authorized

I am redirecting to my .NET 8 application from other application from there I am getting the userid and filling the same in my session. I am adding the userid in claims.

When I am not directly using the URL, still I am able to see the page, I am not redirected to the unauthorized page.

Here's my code - program.cs:

using CCP_Core.Service;
using Core.Service;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.Office.Interop.Excel;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor(); 

var connectionString = builder.Configuration.GetConnectionString("connection");

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/Home/UnAuthorized"; // Set your login path here
        });

builder.Services.AddScoped(provider => new DataService(connectionString));
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(20);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();


app.UseSession();

if (app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseExceptionHandler("/Home/Error");
app.UseRouting();
app.UseStaticFiles();

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

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

app.MapRazorPages();
app.Run();

This is the HomeController code:

using System.Data;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using CCP_Core.Model;
using CCP_Core.Service;
using Core.Model;
using Core.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using OfficeOpenXml;

namespace Core.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly DataService _dataService;
        private readonly IWebHostEnvironment _environment;

        public HomeController(DataService dataService, IWebHostEnvironment environment)
        {
            _dataService = dataService;
            _environment = environment;
        }

        [HttpGet]
        public string Index()
        {
            return "Welcome";
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Index(IFormCollection fc)
        {
            string userid = fc["userid"];
            string token = fc["token"];
            string url = fc["url"];

            string msg = _dataService.GetTermSheetData(userid, token);

            if (msg == "SUCCESS")
            {
                // For menu system name 
                HttpContext.Session.SetString("userid", userid);

                List<Claim> claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, userid));
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userid));

                ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                HttpContext.SignInAsync(claimsPrincipal);

                if (!string.IsNullOrEmpty(url))
                {
                    return("Welcome");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            else
            {
                HttpContext.Session.SetString("userid", "");
            }

            return RedirectToAction("Index");
        }
        
        [Authorize]
        public async Task<IActionResult> Welcome()
        {
            return View();
        }

        [AllowAnonymous]
        public async Task<ActionResult> UnAuthorized()
        {
            return View();
        }
    }
}   

Am I missing something?

I am able to open Home/Welcome directly, even without authorization.

Upvotes: 0

Views: 32

Answers (1)

Rahul Aggarwal
Rahul Aggarwal

Reputation: 291

Based on the comment of @Ruikai Feng, I cleared/deleted the cookies while Logging out

foreach (var cookie in Request.Cookies.Keys)
{
    Response.Cookies.Delete(cookie);
}

Upvotes: 0

Related Questions