使用.Net Core中的Windows Authenticated app从SQL填充自定义声明

K7B*_*uoy 1 authorization claims-based-identity asp.net-core

场景 - 使用SQL Server管理应用程序特定权限和扩展用户身份的Active Directory中的.Net Core Intranet应用程序.

迄今为止的成功 - 用户已通过身份验证,并且可以使用Windows声明(名称和组).Identity.Name可用于从具有扩展属性的数据库返回域用户模型.

问题和问题 - 我试图填充一个自定义声明属性"Id",并通过ClaimsPrincipal全局提供.到目前为止,我已经查看了ClaimsTransformation,但没有取得多大成功.在其他文章中,我已经读过你必须在登录之前添加声明,但这真的可以吗?这意味着完全依赖AD满足所有索赔,情况确实如此吗?

下面是我在HomeController中的简单代码.我正在访问数据库,然后尝试填充ClaimsPrincipal,然后返回域用户模型.我认为这可能是我的问题所在,但我是.net的授权新手,并努力让我的头脑索赔.

非常感谢所有的帮助

现行代码:

public IActionResult Index()
        {
            var user = GetExtendedUserDetails();
            User.Claims.ToList();
            return View(user);
        }

        private Models.User GetExtendedUserDetails()
        {
            var user = _context.User.SingleOrDefault(m => m.Username == User.Identity.Name.Remove(0, 6));
            var claims = new List<Claim>();

            claims.Add(new Claim("Id", Convert.ToString(user.Id), ClaimValueTypes.String));
            var userIdentity = new ClaimsIdentity("Intranet");
            userIdentity.AddClaims(claims);
            var userPrincipal = new ClaimsPrincipal(userIdentity);

            return user;
        }
Run Code Online (Sandbox Code Playgroud)

更新:

我已经注册了ClaimsTransformation

app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));
Run Code Online (Sandbox Code Playgroud)

并根据此github查询构建如下所示的ClaimsTransformer

https://github.com/aspnet/Security/issues/863

public class ClaimsTransformer : IClaimsTransformer
{
    private readonly TimesheetContext _context;
    public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
    {

        System.Security.Principal.WindowsIdentity windowsIdentity = null;

        foreach (var i in context.Principal.Identities)
        {
            //windows token
            if (i.GetType() == typeof(System.Security.Principal.WindowsIdentity))
            {
                windowsIdentity = (System.Security.Principal.WindowsIdentity)i;
            }
        }

        if (windowsIdentity != null)
        {
            //find user in database
            var username = windowsIdentity.Name.Remove(0, 6);
            var appUser = _context.User.FirstOrDefaultAsync(m => m.Username == username);

            if (appUser != null)
            {

                ((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim("Id", Convert.ToString(appUser.Id)));

                /*//add all claims from security profile
                foreach (var p in appUser.Id)
                {
                    ((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim(p.Permission, "true"));
                }*/

            }

        }
        return await System.Threading.Tasks.Task.FromResult(context.Principal);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到NullReferenceException:尽管先前已返回域模型,但对象引用未设置为对象错误的实例.

使用STARTUP.CS

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Birch.Intranet.Models;
using Microsoft.EntityFrameworkCore;

namespace Birch.Intranet
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthorization();

            // Add framework services.
            services.AddMvc();
            // Add database
            var connection = @"Data Source=****;Initial Catalog=Timesheet;Integrated Security=True;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            services.AddDbContext<TimesheetContext>(options => options.UseSqlServer(connection));

            // Add session
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(60);
                options.CookieName = ".Intranet";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

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

            app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));

            app.UseSession();
            app.UseDefaultFiles();
            app.UseStaticFiles();

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

ade*_*lin 5

您需要使用IClaimsTransformer依赖注入.

    app.UseClaimsTransformation(async (context) =>
    {
        IClaimsTransformer transformer = context.Context.RequestServices.GetRequiredService<IClaimsTransformer>();
        return await transformer.TransformAsync(context);
    });

    // Register
    services.AddScoped<IClaimsTransformer, ClaimsTransformer>();
Run Code Online (Sandbox Code Playgroud)

而且需要注入DbContextClaimsTransformer

public class ClaimsTransformer : IClaimsTransformer
{
    private readonly TimesheetContext _context;
    public ClaimsTransformer(TimesheetContext  dbContext)
    {
        _context = dbContext;
    }
    // ....
 }
Run Code Online (Sandbox Code Playgroud)