Auto Login on debug ASP.Net Core 2.1

吃可爱长大的小学妹 提交于 2019-12-23 18:18:36

问题


I am trying to auto login for debugging purposes on an ASP.net core 2.1 application I've built.

Getting the Error :

HttpContext must not be null.

The code below sits in the Startup.cs file

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider ServiceProvider)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseCookiePolicy();

        CreateRoles(ServiceProvider).Wait();

        if (env.IsDevelopment())
        {
            DeveloperLogin(ServiceProvider).Wait();
        }
    }


    private async Task DeveloperLogin(IServiceProvider serviceProvider){

        var UserManager = serviceProvider.GetRequiredService<UserManager<User>>();
        var signInManager = serviceProvider.GetRequiredService<SignInManager<User>>();

        var _user = await UserManager.FindByNameAsync("test@gmail.com");

        await signInManager.SignInAsync(_user, isPersistent: false);

    }

This is an extension of sorts on another question I asked a while back about Windows Authentication on a Mac. Because of the nature of the application I had added Core Identity for role management even though the application still only uses Windows Auth.

Since I migrated to a Macbook for development I'm trying to autologin on build for debugging using the already existing Identity since there is no Windows Auth which is where the DeveloperLogin function fits in but I get the error mentioned above.

StackTrace:

    System.AggregateException: "One or more errors occurred. (HttpContext must not be null.)" 
---> System.Exception {System.InvalidOperationException}: "HttpContext must not be null."
    at Microsoft.AspNetCore.Identity.SignInManager`1.get_Context()
    at Microsoft.AspNetCore.Identity.SignInManager`1.SignInAsync(TUser user, AuthenticationProperties authenticationProperties, String authenticationMethod)
    at myApp.Startup.DeveloperLogin(IServiceProvider serviceProvider) in /Users/user/Documents/Repositories/myApp/myApp/Startup.cs:135

回答1:


For HttpContext, it only exists during http request pipeline. There is no HttpContext in Configure method, you need to refer the code during middleware.

For using Identity, you need to use app.UseAuthentication();.

Follow steps below with sigin with Identity.

  • Configure request pipeline.

        app.UseAuthentication();
        if (env.IsDevelopment())
        {
            app.Use(async (context, next) =>
            {
                var user = context.User.Identity.Name;
                DeveloperLogin(context).Wait();
                await next.Invoke();
            });
        }
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    

    Note: you need to call app.UseAuthentication();, the order is import.

  • DeveloperLogin

        private async Task DeveloperLogin(HttpContext httpContext)
    {
    
        var UserManager = httpContext.RequestServices.GetRequiredService<UserManager<IdentityUser>>();
        var signInManager = httpContext.RequestServices.GetRequiredService<SignInManager<IdentityUser>>();
    
        var _user = await UserManager.FindByNameAsync("Tom");
    
        await signInManager.SignInAsync(_user, isPersistent: false);
    
    }
    


来源:https://stackoverflow.com/questions/53514318/auto-login-on-debug-asp-net-core-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!