3

setup with Asp.net & .Net Core 3.1, I have upgraded a previous Identity system using UserName/Password with Roles to use Windows Authentication. I have created a ClaimsTransformation which gets the windows Identity and creates a new ClaimsPrincipal with the users associated roles. This part is working My startup.cs looks like this (some parts removed)

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddTransient<IClaimsTransformation, KiwaClaimsTransformation>();

     services.AddAuthentication(IISDefaults.AuthenticationScheme);

     services.AddAuthorization();

     ...
     services.AddControllers();

     services.AddControllersWithViews()
      .AddSessionStateTempDataProvider();
 }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
            ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
 {
       ...

       app.UseStaticFiles();

       app.UseCookiePolicy();

       app.UseRouting();

       app.UseAuthentication();

       app.UseAuthorization();

       app.UseEndpoints(endpoints =>
       {
           endpoints.MapControllers();
           endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
           // catch all for not found
           endpoints.MapControllerRoute("NotFound", "{*url}",
                    new {controller = "Error", action = "ResourceNotFound"});
       });

       ...
  }

The ClaimsTransformation looks like this

 public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var identity = (ClaimsIdentity)principal.Identity;
            if (identity == null) return principal;

            var userName = _config["LoginUserName"];
            if (userName == null)
            {
                userName = identity.Name;
                if (userName == null) return principal;
            }

            // need to go and build the Roles claims for the user based on the User Name as a lookup on User table 
            var claims = new List<Claim>
            {
                new Claim(@"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", userName, "Name")
            };
            claims.AddRange(_userLookup.GetUserRolesByNetworkId(userName)
                .Select(role => new Claim(ClaimTypes.Role, role)));

            //The claim identity uses a claim with the claim type below to determine the name property.
            // Get User Roles from database and add to list of claims.
            var newClaimsIdentity = new ClaimsIdentity(claims, "Kerberos", "", "http://schemas.microsoft.com/ws/2008/06/identity/claims/role");

            return new ClaimsPrincipal(new ClaimsPrincipal(newClaimsIdentity));
        }

I have a basic HomeController which looks like this

  public class HomeController : Controller
    {
        private readonly LoggedOnUser _loggedOnUser;

        public HomeController(LoggedOnUser loggedOnUser)
        {
            _loggedOnUser = loggedOnUser;
        }

        [Authorize]
        [HttpGet]
        public IActionResult Index()
        {
            // check and make sure the user is allowed in 
            if (!_loggedOnUser.IsValidKiwaUser)
            {
                return RedirectToActionPermanent("NotAuthorised");
            }
            return View();
        }

        [Authorize]
        public IActionResult OperationResults()
        {
            ViewBag.Title = (string)TempData["Title"];
            string jsonString = (string)TempData["OperationResults"];
            if (string.IsNullOrWhiteSpace(jsonString))
            {
                return RedirectToPage("/Error/NoResults");
            }
            return View(JsonConvert.DeserializeObject<List<OperationResult>>(jsonString));
        }


        public IActionResult NotAuthorised()
        {
            return View();
        }

All of the Controllers have [Authorize(Role="...")], and the Authorisation is happening correctly and the Roles are added as claims via the ClaimsTransformation. The issue i am having is that if i hit the root of the Website (debugging this is https://localhost:44391), then the routing sends me to the NotAuthorised page on the controller??? It should be default go to https://localhost:44391/Home/index as defined in the default Endpoint. If I type in https://localhost:44391/Home/index it works and shows the correct main landing page, but if i do NOT include the https://localhost:44391/Home/index in its entirety then it comes back as unauthorized.

Am i missing something here? Also can i turn

Grant Nilsson
  • 565
  • 5
  • 18

1 Answers1

2

I eventually found the issue. During the transition to change over to Windows Authentication, i had left the cookie support i the product. But what this had done was store the starting page as being the NotAuthorised page. Clearing the cookie (and subsequently removing the cookie support from the app), fixed the issue and the Roles were evaluated all the time. Hence why I used a lookup (memory Cache) for accessing the user and their claims - as it gets called for all User requests

Oh by the way. The check for _loggedOnUser.IsValidKiwaUser in the HomeController/Index is actually no longer required if you use this as an example

Grant Nilsson
  • 565
  • 5
  • 18