为什么用户未经过身份验证?

时间:2015-08-20 09:36:47

标签: asp.net-core asp.net-core-mvc claims-based-identity

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
        }
    }

帐户管理员:

[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);
        }

那是我的代码,从我记忆中它曾经工作但现在我不知道该怎么做了。

任何人都可以了解为什么用户未经过身份验证?

2 个答案:

答案 0 :(得分:0)

尝试取消引用options.AutomaticAuthentication = true;以确保自动调用Cookie中间件,并在请求到达时对用户进行身份验证。

您还应该在await之前添加Context.Authentication.SignInAsync关键字,因为它是异步操作。不等待它可能会导致可怕的竞争状况。

答案 1 :(得分:0)

我解决了! options.CookieSecure = CookieSecureOption.Always;是问题所在,因为这意味着您必须使用https而不是http。

相关问题