IdentityServer4 и ASP.NET Core 2.2 Интеграция с ASP.NET Identity - PullRequest
0 голосов
/ 25 февраля 2019

Получение этой ошибки

InvalidOperationException: Нет службы для типа 'Microsoft.AspNetCore.Identity.UserManager`1 [Microsoft.AspNetCore.Identity.IdentityUser]'.

Я пытаюсь получить identityserver и пользовательский интерфейс asp.net в одном проекте.

Следуя этой статье http://docs.identityserver.io/en/dev/quickstarts/6_aspnet_identity.html#new-project-for-asp-net-identity, вы получите необходимый дополнительный код.Я проделал следующие шаги

  1. Создание приложения ASP.NET Core 2.2 MVC, аутентификация для одной учетной записи

  2. Протестировал его, чтобы убедиться, чтовсе работает, зарегистрировал пользователя, залогинился, все работает хорошо.

  3. Добавлен пакет nuget IdentityServer4.AspnetIdentity

  4. Добавлена ​​конфигурация.cs файл ниже

    public static class Config
    {
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Email(),
        };
    }
    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("eventsapi", "Events Api")
        };
    }
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "client",
    
                // no interactive user, use the clientid/secret for authentication
                AllowedGrantTypes = GrantTypes.ClientCredentials,
    
                // secret for authentication
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
    
                // scopes that client has access to
                AllowedScopes = { "eventsapi" }
            }
        };
    }
    }
    
  5. Добавлен ApplicationUser.cs

    public class ApplicationUser:IdentityUser
    {
    }
    
  6. Изменен Startup.cs (скомментированный код сгенерирован)

      public class Startup
       {
         public Startup(IConfiguration configuration)
       {
          Configuration = configuration;
       }
    
    public IConfiguration Configuration { get; }
    
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
    
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
    
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        /*
        services.AddDefaultIdentity<IdentityUser>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        */
        //REPLACED ABOVE
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
    
    
    
    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
        //ADDDED
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<ApplicationUser>();
    
    }
    
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
             app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
    
        //app.UseAuthentication();
        //REPLACED ABOVE
        app.UseIdentityServer();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    }

1 Ответ

0 голосов
/ 26 февраля 2019

Для этой ошибки попробуйте изменить IdentityUser на Views\Shared\_LoginPartial.cshtml.

@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>
    </li>
    <li class="nav-item">
        <form  class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
            <button  type="submit" class="nav-link btn btn-link text-dark">Logout</button>
        </form>
    </li>
}
else
{
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
}
</ul>

И затем вам необходимо зарегистрировать AddDefaultUI, который используется для обработки запроса области идентификации к действию в Startup.cs, как

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...