Thursday, February 6, 2020

ClaimsPrincipal in C# magically manages users in such a manner that ReST calls to the same app as the app holding the MVC Razor views where one logged in to begin with have user specs.

My head explodes! How does this work? It must be recognizing something specific in the browser session based on the header communicated. Wacky! Well now there will be no more state across a mishmash of session and cache. If you set a breakpoint at return below on line fifteen, the two variables in the two previous lines get hydrated if you are logged in.

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace Portal.Web.Controllers
{
   [Route("api/[controller]")]
   [ApiController]
   public class JaeschkeController : ControllerBase
   {
      [HttpGet]
      public IEnumerable<string> Get()
      {
         var isInsider = User.IsInRole("Insider");
         var myId = User.Claims.FirstOrDefault(x => x.Type == "MyId").Value;
         return new string[] { "value1", "value2" };
      }
   }
}

 
 

Microsoft.AspNetCore.Mvc.Controller which has the support for views inheirts from Microsoft.AspNetCore.Mvc.ControllerBase (thinner) which has the ClaimsPrincipal called User hanging off of it. My superior thinks the magic is tied to the antiforgery token of MVC.

No comments:

Post a Comment