Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to add custom Claims to Windows Authenication Application?

$
0
0

Hi,

I'm developing an Intranet Application in ASP.Net v5 and want to use Windows Authentication. However I also need to add some custom Claims from a database to the principal identity. 

I've got this working using ClaimsTransformation Middleware "UseClaimsTransformation" but the issue I have is that every request will hit this and make unnecessary database calls.  

Is this the correct approach? or should I be using a different method for adding custom claims when using Windows Authentication? 

My Startup Config: 

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseIISPlatformHandler();

            var listener = app.ServerFeatures.Get<WebListener>();

            if (listener != null)
            {
                listener.AuthenticationManager.AuthenticationSchemes =
                    AuthenticationSchemes.NTLM;
            }

            app.UseStaticFiles();

            app.UseClaimsTransformation(o => o.Transformer = new MyClaimsTransformer());

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Custom Transformer

 public virtual Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var name = principal.Identity.Name;
            if (principal.Identity.IsAuthenticated)
            {             
                var optionsBuilder = new DbContextOptionsBuilder();
                optionsBuilder.UseSqlServer("Server=xxxx;Database=xxxx;Trusted_Connection=True;MultipleActiveResultSets=true");  
                using (var _db = new ApplicationDbContext(optionsBuilder.Options))
                {
                    // get from db
                    var users = _db.UserHistory.Where(p => p.Username == principal.Identity.Name);
                    (principal.Identity as ClaimsIdentity).AddClaim(new Claim("Office", users.Select(p => p.Office).SingleOrDefault()));
                }
            }
            return Task.FromResult(principal);
        }


Viewing all articles
Browse latest Browse all 9386

Trending Articles