Не работает авторизация через куки ASP. NET Core на Linux. В чем проблема?

Всем привет. Столкнулся с проблемой при развертывании ASP.NET Core на Linux, а именно с тем, что на сервере есть авторизация через куки, но она работает только когда сервер запущен под Windows, при разворачивании на Linux, когда на сервер уходит данные о логине с паролем, то вылетает код 404 как-будто бы сервер не знает о методе авторизации. Кто может подсказать в чем проблема?

Исходники:

Контроллер
public class AccountController : Controller
    {
        private readonly DbSubjects database;

        private readonly IConfiguration configuration;

        public AccountController(DbSubjects database, IConfiguration configuration)
        {
            this.database = database;
            this.configuration = configuration;
        }

        [HttpGet]
        public IActionResult Login() => View("Login");

        [HttpPost]
        public async Task<IActionResult> Authenticate(LoginModel model)
        {
            if (!Domain.ValidateAdmin(model.Login, model.Password, configuration))
            {
                User user = await database
                    .Users
                    .FirstOrDefaultAsync(u => u.Login == model.Login && u.Password == model.Password);

                if (user is null)
                   return RedirectToAction("Login", "Account");
            }

            var claims = new List<Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, model.Login)
            };

            ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));

            return RedirectToAction("AllList", "Common");
        }

        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login", "Account");
        }
    }


Класс Startup
public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string ConnectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<DbSubjects>(options => options.UseSqlServer(ConnectionString));

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = new PathString("/account/login");
                });

            services.Configure<IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
            });

            services.AddMvc();
        }

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

            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseCors(builder =>
            {
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowAnyOrigin();
                builder.AllowCredentials();
            });

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


Вьюшка:
@{
    ViewData["Title"] = "Авторизация";
    Layout = "~/Views/Shared/_LoginLayout.cshtml";
}

<form method="post" asp-controller="Account" asp-action="Authenticate" class="registration-form">
    <div class="form-group" style="margin-top:25px;">
        <label for="login">Логин</label>
        <input class="form-control" id="login" name="model.login" placeholder="Логин">
        <small id="loginHelp" class="form-text text-muted">Логин от доменной учетной записи</small>
    </div>
    <div class="form-group">
        <label for="password">Пароль</label>
        <input type="password" class="form-control" id="password" name="model.password" placeholder="Пароль">
        <small id="passwordHelp" class="form-text text-muted">Пароль от доменной учетной записи</small>
    </div>
    <button type="submit" class="btn btn-primary">Войти</button>
</form>
  • Вопрос задан
  • 289 просмотров
Решения вопроса 1
@perfectdaemon
Как вариант, убедиться, что регистр имен файлов совпадает с заданным при редиректе:
return RedirectToAction("AllList", "Common");

Т.е. вьюшка, отдаваемая контроллером Common, метода AllList называется ровно так, как контроллер пытается ее найти.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы