При первом входе в систему пользовательский контекст SignInManager имеет нулевое значение - PullRequest
0 голосов
/ 31 января 2020

У меня возникла очень странная проблема, ответ на которую мне не очень очевиден. Я пытаюсь реализовать AS PNET CORE Identities (3.1), используя SignInManager и UserManager. Когда signinmanager пытается вызвать метод SignInWithClaimsAsyn c, он умирает с сообщением об ошибке, указывающим, что HTTPContext не должен быть нулевым. Я добавил HTTPContextAccessor, используя метод расширения, чтобы попытаться выяснить, не решило ли это проблему, но нет никаких изменений в поведении.

Ниже приведены соответствующие фрагменты кода:

Запуск .cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Common.Abstract.ServiceBus.Startup;
using Microsoft.Azure.ServiceBus;
using Common.Interfaces.ServiceBus;
using Common.Abstract.ServiceBus.Services;
using CSEC.Entity;
using Microsoft.EntityFrameworkCore;
using CSEC.Core.Services;
using Microsoft.AspNetCore.Identity;
using System;
using CSEC.Core.Models;
using CSEC.Core.Stores;
using Microsoft.AspNetCore.Http;

namespace CSEC.Core
{
    public class Startup : StartupServiceBusBase
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

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

            // HTTP Context Accessor
            services.AddHttpContextAccessor();

            // EF Core
            services.AddDbContext<CSEC_DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("CONTEXT")));

            // Service Bus
            services.AddScoped<ServiceBusConnection>((serviceProvider) => this.ResolveServiceBusNode(serviceProvider));
            services.AddScoped<IServiceBusService, ClientBusService>();

            // Supporting Services
            services.AddScoped<IUserService, UserService>();
            services.AddScoped<ISecurityService, SecurityService>();
            services.AddScoped<IImportExportService, ImportExportService>();

            // Razor Page Mapping
            services.AddRazorPages();

            // Identity
            services.AddTransient<IPasswordHasher<ApplicationUser>, PasswordHasher>();
            services.AddTransient<IUserStore<ApplicationUser>, UserStore>();
            services.AddTransient<IRoleStore<ApplicationRole>, RoleStore>();

            services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
            {
                options.SignIn.RequireConfirmedEmail = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;
            })
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
                options.LoginPath = "/Index";
                options.AccessDeniedPath = "/Error";
                options.SlidingExpiration = true;
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseSession();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

Razor PageModel (откуда вызывается функция)

 [AllowAnonymous]
    public class IndexModel : PageModel
    {
        [BindProperty]
        public string UserName { get; set; }
        [BindProperty]
        public string Password { get; set; }
        public bool Reverify { get; set; }
        public string Email { get; set; }
        public string ReverificationToken { get; set; }

        // Private
        private readonly ILogger<IndexModel> _logger;
        private readonly UserManager<ApplicationUser> _UserManager;
        private readonly SignInManager<ApplicationUser> _SignInManager;

        public IndexModel(ILogger<IndexModel> logger, UserManager<ApplicationUser> um, SignInManager<ApplicationUser> sm)
        {
            _logger = logger;
            _UserManager = um;
            _SignInManager = sm;
            Reverify = false;
        }

        public void OnGet()
        {

        }

        public async void OnPost()
        {
            var result = await _SignInManager.PasswordSignInAsync(UserName, Password, true, false);
            if (result.Succeeded)
            {
                RedirectToPage("", "");
            }
            else
            {

            }
        }
    }

стек ошибок:

   at Microsoft.AspNetCore.Identity.SignInManager`1.get_Context()
   at Microsoft.AspNetCore.Identity.SignInManager`1.<SignInWithClaimsAsync>d__33.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNetCore.Identity.SignInManager`1.<SignInOrTwoFactorAsync>d__59.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.SignInManager`1.<PasswordSignInAsync>d__38.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.SignInManager`1.<PasswordSignInAsync>d__39.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at CSEC.Core.Pages.IndexModel.<OnPost>d__25.MoveNext() in D:\Workspaces\Azure DevOps\CSEC\CSEC.Core\Pages\Index.cshtml.cs:line 46
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__139_1(Object state)
   at System.Threading.QueueUserWorkItemCallback.<>c.<.cctor>b__6_0(QueueUserWorkItemCallback quwi)
   at System.Threading.ExecutionContext.RunForThreadPoolUnsafe[TState](ExecutionContext executionContext, Action`1 callback, TState& state)
   at System.Threading.QueueUserWorkItemCallback.Execute()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Испытанные элементы: - Внедрение контекста прямо в signinmanager. Это приводит к удалению объекта.

Я могу предоставить хранилища пользователя / роли при необходимости.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...