Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Login on debug ASP.Net Core 2.1

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("[email protected]");

        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
like image 926
user2806570 Avatar asked Nov 28 '18 07:11

user2806570


1 Answers

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);
    
    }
    
like image 100
Edward Avatar answered Oct 19 '22 04:10

Edward