将Aspnetcore身份与IdentityServer4,Active Directory和MongoDB结合使用

时间:2018-12-06 18:22:26

标签: mongodb asp.net-core identityserver4 asp.net-core-identity

所需流量:

  1. 用户未登录时,点击具有[Authorize]属性的webapi或mvc控制器。
  2. 请求被重定向到IdentityServer4的登录页面
  3. 用户输入其Active Directory凭据,然后单击登录
  4. 用户将其SubjectId设置为用户名后重定向到受保护的mvc控制器或api
  5. MVC / WebApi应用程序利用AspNet身份从MongoDB中拉出一个自定义用户对象,以便在控制器方法中使用。

要完成此操作,我目前尝试的是将IdentityServer4 Quickstart与IdentityServer.LdapExtension nuget包(源:IdentityServer.LdapExtension)一起配置为Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {

        //services.AddIdentityCore<Api.AppUser>();
        services.AddIdentity<Api.AppUser, Api.AppRole>()
            .AddMongoDbStores<Api.AppUser, Api.AppRole, string>
            (
                "mongodb://localhost:27017",
                "MongoDbTests"
            )
            .AddDefaultTokenProviders();

        services.AddMvc();

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            ////.AddSigningCredential(...) // Strongly recommended, if you want something more secure than developer signing (Read The Manual since it's highly recommended)
            .AddInMemoryIdentityResources(InMemoryInitConfig.GetIdentityResources())
            .AddInMemoryApiResources(InMemoryInitConfig.GetApiResources())
            .AddInMemoryClients(InMemoryInitConfig.GetClients())
            .AddLdapUsers<ActiveDirectoryAppUser>(Configuration.GetSection("ldapActiveDirectory"), UserStore.InMemory)
            .AddAspNetIdentity<Api.AppUser>();
    }

    public void Configure(IApplicationBuilder app)
    {
        if (Env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseIdentityServer();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }

这可以对ActiveDirectory进行身份验证,并且可以与IdentityServer4中的示例MVC客户端一起使用。您可能还会注意到,我在AspNetCore.Identity.MongoDbCore nuget包(源:AspNetCore.Identity.MongoDbCore)中添加了配置代码(AddMongoDbStores<Api.AppUser, Api.AppRole, string>...

经过一段时间的努力,我最终要做的是修改IdentityServer4 Quickstart的AccountController中的代码,以在SignInAsync调用之前添加以下行:

var mongouser = await _mongoUserStore.FindByIdAsync(user.SubjectId, CancellationToken.None);
if(mongouser == null)
{
  mongouser = new AppUser();
  mongouser.UserName = user.Username;
  mongouser.Id = user.Username;
  await _mongoUserStore.CreateAsync(mongouser, CancellationToken.None);
 }

这确实会在用户首次登录时在mongodb数据库中创建用户。我还设置了MVC客户端,以使MongoDb用户存储具有相同的用户和角色类。但是,当我重定向回MVC客户端的控制器时,出现以下错误:

Error Message

我尝试通过以下答案解决此问题:c# - Value cannot be null. Parameter name: value, CreateIdentityAsync,但是一旦我给SecurityStamp赋了一个值,那只会导致无休止的重定向循环。

我至少正在寻找有关下一步应该寻找的指导?

0 个答案:

没有答案
相关问题