0

Startup.cs:

public class Startup
    {
        public IConfiguration Configuration { get; set; }

        public Startup(IApplicationEnvironment env)
        {
            var builder = new ConfigurationBuilder(env.ApplicationBasePath)
                        .AddJsonFile("Config.json")
                        .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<Constants>(constants =>
            {
                constants.DefaultAdminUsername = Configuration["DefaultAdminUsername"];
                constants.DefaultAdminPassword = Configuration["DefaultAdminPassword"];
            });

            //services.AddTransient<EF.DatabaseContext>(x => EF.DAL.RepositoryIoCcontainer.GetContext(Configuration["Data:DefaultConnection:ConnectionString"]));

            EF.DatabaseContext.ConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];

            services.AddAuthorization();
            services.AddAuthentication();
            services.AddMvc();
            services.AddSession();
            services.AddCaching();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Warning);

            #region Configure the HTTP request pipeline.
            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseErrorPage(new ErrorPageOptions() { SourceCodeLineCount = 10 });
                app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseErrorHandler("/Home/Error");
            }

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            app.UseSession();

            // Add cookie-based authentication to the request pipeline.
            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthentication = true;
                options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.AccessDeniedPath = new PathString("/Account/Denied");
                options.CookieName = "WNCT Coockie";
                options.CookieSecure = CookieSecureOption.Always;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(30);                
                options.SlidingExpiration = true;                
                options.LoginPath = new PathString("/Account/Login");
                options.LogoutPath = new PathString("/Account/Logout");
            });

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            #endregion
        }
    }

Account controller:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async System.Threading.Tasks.Task<IActionResult> Login(LoginModel model, string returnUrl)
        {
            LDAP.ALUHTTPAuthentication auth = new LDAP.ALUHTTPAuthentication(model.UserName, model.Password);

            if (ModelState.IsValid && auth.IsAuthenticated)
            {
                IUserServices ius = RepositoryIoCcontainer.GetImplementation<IUserServices>();
                //check if user is registered in the tool
                User user = ius.Get(csl: model.UserName);

                if (false)//user == null)
                {

                }
                else
                {
                    //set user claim
                    var claims = new List<Claim>
                    {
                        //new Claim(ClaimTypes.IsPersistent, "true", "bool"),
                        new Claim(ClaimTypes.Role, "somerole"),
                        new Claim(ClaimTypes.Name, "thename")
                        //new Claim("Monitoring", user.UserFeatures.First(x => x.Feature.Name == "Monitoring").Allowed.ToString(), "bool")
                    };                    

                    var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));

                    await Context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
                }

                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "You cannot log in with the provided credentials. Please check, and try again.");

            return View(model);
        }

That was my code, and from what I remember it used to work but now I don't know what's up.

Can anyone shed some light on why isn't the user authenticated?

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
Mihai Bratulescu
  • 1,915
  • 3
  • 27
  • 43

2 Answers2

0

Try unquoting options.AutomaticAuthentication = true; to make sure the cookies middleware is automatically invoked and authenticates the user when a requests arrives.

You should also add the await keyword before Context.Authentication.SignInAsync since it's an async operation. Not awaiting it may result in a terrible race condition.

Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
  • You should try to share your whole Startup class and at least one controller where you're using cookies authentication. It's hard to figure out why it doesn't work with minimal details. – Kévin Chalet Aug 20 '15 at 11:55
  • You don't need to post two comments or create a duplicate question for that... Your cookie name has a white space, which is not allowed: http://stackoverflow.com/questions/1969232/allowed-characters-in-cookies. I'm not saying it's the root cause of your issue, but it's probably worth to try. – Kévin Chalet Aug 28 '15 at 00:54
  • Sorry for the double post but this question got old. I removed the white space but it's still not authenticating. Any more ideas? – Mihai Bratulescu Aug 31 '15 at 12:48
0

I solved it! options.CookieSecure = CookieSecureOption.Always; was the problem because this means you must use https not http.

Mihai Bratulescu
  • 1,915
  • 3
  • 27
  • 43