1

整个身份概念的新手,但我已经进行了几次 Google 搜索,但没有找到我认为合适的回复。

我将 .NET Core 1.0.0 与 EF Core 和 IdentityServer 4 (ID4) 一起使用。ID4 位于单独的服务器上,我在客户端获得的唯一信息是声明。我想访问完整的(扩展的)用户配置文件,最好从 User.Identity 访问。

那么如何设置以便 User.Identity 填充 ApplicationUser 模型上的所有属性,而无需每次都发送数据库请求?我希望将信息存储在身份验证缓存中,直到会话结束。

我不想做的是在每个控制器中设置一个查询来获取附加信息。客户端上的所有控制器都将从基本控制器继承,这意味着如果有必要,我可以 DI 一些服务。

提前致谢。

客户

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookies"
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = "Cookies",

            Authority = Configuration.GetSection("IdentityServer").GetValue<string>("Authority"),
            RequireHttpsMetadata = false,
            ClientId = "RateAdminApp"
        });

ID4

app.UseIdentity();

app.UseIdentityServer();

services.AddDeveloperIdentityServer()
            .AddOperationalStore(builder => builder.UseSqlServer("Server=localhost;Database=Identities;MultipleActiveResultSets=true;Integrated Security=true", options => options.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name)))
            .AddConfigurationStore(builder => builder.UseSqlServer("Server=localhost;Database=Identities;MultipleActiveResultSets=true;Integrated Security=true", options => options.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name)))
            .AddAspNetIdentity<ApplicationUser>();

应用用户模型

public class ApplicationUser : IdentityUser
{
    [Column(TypeName = "varchar(100)")]
    public string FirstName { get; set; }
    [Column(TypeName = "varchar(100)")]
    public string LastName { get; set; }
    [Column(TypeName = "nvarchar(max)")]
    public string ProfilePictureBase64 { get; set; }
}
4

1 回答 1

0

If you want to transform claims on the identity server, for your case(you use aspnet identity) overriding UserClaimsPrincipalFactory is a solution(see Store data in cookie with asp.net core identity).

public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public AppClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager,
        IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
    {
    }

    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
             new Claim("FirstName", user.FirstName)
        });

        return principal;
    }
}

// register it
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();

Also you can use events(on the client application) to add extra claims into cookie, it provides claims until the user log out.

There are two(maybe more than) options:

First using OnTicketReceived of openidconnect authentication:

    app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
    {
        AuthenticationScheme = "oidc",
        SignInScheme = "Cookies",

        Authority = Configuration.GetSection("IdentityServer").GetValue<string>("Authority"),
        RequireHttpsMetadata = false,
        ClientId = "RateAdminApp",
        Events = new OpenIdConnectEvents
        {
           OnTicketReceived = e =>
           {
               // get claims from user profile
               // add claims into e.Ticket.Principal
               e.Ticket = new AuthenticationTicket(e.Ticket.Principal, e.Ticket.Properties, e.Ticket.AuthenticationScheme);

               return Task.CompletedTask;
            }
        }
    });

Or using OnSigningIn event of cookie authentication

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
     AuthenticationScheme = "Cookies",
     Events = new CookieAuthenticationEvents()
     {
         OnSigningIn = async (context) =>
         {
             ClaimsIdentity identity = (ClaimsIdentity)context.Principal.Identity;
             // get claims from user profile
             // add these claims into identity
         }
     }
});

See similar question for solution on the client application: Transforming Open Id Connect claims in ASP.Net Core

于 2016-10-07T07:50:42.167 回答