【问题标题】:Populate custom claim from SQL with Windows Authenticated app in .Net Core使用 .Net Core 中的 Windows Authenticated 应用程序从 SQL 填充自定义声明
【发布时间】:2016-10-28 12:38:34
【问题描述】:

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

迄今为止的成功 - 用户已通过身份验证并且 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;
        }

更新:

我已注册 ClaimsTransformation

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

并根据此 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);
    }
}

但是我得到 NullReferenceException: Object reference not set to an instance of an object error 尽管之前已经返回了域模型。

使用 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?}");
            });
        }
    }
}

【问题讨论】:

  • 你能发布 startup.cs 吗?
  • @ademcaglin 在上面的编辑中完成。我发现 dbcontext 在课堂上变得不可用......这将使访问数据库变得非常困难。 :-) 不知道为什么。

标签: asp.net-core authorization claims-based-identity


【解决方案1】:

您需要使用 IClaimsTransformer 进行依赖注入。

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

    // Register
    services.AddScoped<IClaimsTransformer, ClaimsTransformer>();

并且需要在ClaimsTransformer中注入DbContext

public class ClaimsTransformer : IClaimsTransformer
{
    private readonly TimesheetContext _context;
    public ClaimsTransformer(TimesheetContext  dbContext)
    {
        _context = dbContext;
    }
    // ....
 }

【讨论】:

  • ClaimTransformer 类中的数据库上下文 (_context) 仍然为空,但感觉是正确的。
  • 你添加了我答案的最后一部分吗?
  • 好吧。真尴尬!不,我没有。我非常感谢你,为此浪费了几个小时。
猜你喜欢
  • 2020-07-24
  • 2017-07-04
  • 2021-05-20
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多