Почему происходит сбой авторизации, когда я публикую sh на IIS в качестве pnet ядра? - PullRequest
0 голосов
/ 06 февраля 2020

Я использовал pnet идентификатор ядра для функции входа в систему в моем веб-приложении. Я опубликовал свое веб-приложение на IIS. Он отлично загружается, но когда я ввожу имя пользователя и пароль и перехожу к методам действий с атрибутом authorize , приложения не работают. Но переименование методов действия с атрибутом AllowAnonymous решает мою проблему !!

Примечание: приложение прекрасно работает с атрибутом authorize, когда я отлаживаю его локально (localhost), как я могу это исправить?

startup.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OnlineExam.Models.LoginModel;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Authorization;
using OnlineExam.Models.CandidateLogin;

namespace OnlineExam
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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)
        {
            //services.AddControllersWithViews();

            services.AddEntityFrameworkSqlServer();
            services.AddIdentity<OnlineExam.Models.UserAccountModel.ApplicationUser, IdentityRole>(options =>
            {
                options.User.AllowedUserNameCharacters = default;
                options.User.RequireUniqueEmail = false;
            })
                    .AddEntityFrameworkStores<Models.UserAccountModel.OnlineExamDBContext>();

            //services.AddMvc();
            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                           .RequireAuthenticatedUser()
                           .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddDbContext<OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<OnlineExam.Models.AdminQuestionModel.OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<CandidateLoginDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<OnlineExam.Models.CandidateExam.CandidateExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddScoped<OnlineExam.Models.UserAccountModel.OnlineExamDBContext>();
            //services.AddScoped<OnlineExam.Controllers.AdminQuestionController>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //    app.UseHsts();
            //}
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}



using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OnlineExam.Models.UserAccountModel;
using System.Web;
using Newtonsoft.Json;
using System.Text.Json;

namespace OnlineExam.Controllers
{
    [AllowAnonymous]
    public class UserAccountsController : Controller
    {
        private readonly OnlineExamDBContext _context;
        private readonly UserManager<OnlineExam.Models.UserAccountModel.ApplicationUser> _userManager;
        private readonly SignInManager<OnlineExam.Models.UserAccountModel.ApplicationUser> _signInManager;

        List<ApplicationUser> userList = new List<ApplicationUser>();

        public UserAccountsController(OnlineExamDBContext context, UserManager<OnlineExam.Models.UserAccountModel.ApplicationUser> userManager, SignInManager<OnlineExam.Models.UserAccountModel.ApplicationUser> signInManager)
        {
            _context = context;
            _userManager = userManager;
            _signInManager = signInManager;
        }

        // GET: UserAccounts
        public async Task<IActionResult> Index()
        {
            return View(await _context.ApplicationUser.ToListAsync());
        }

        // GET: UserAccounts/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var userAccount = await _context.ApplicationUser
                .FirstOrDefaultAsync(m => m.UserAccountId == id);
            if (userAccount == null)
            {
                return NotFound();
            }

            return View(userAccount);
        }

        // GET: UserAccounts/Create
        [HttpGet]
        public IActionResult Create()
        {
            var viewmodel = new ApplicationUser();
            return View(viewmodel);
        }

        // POST: UserAccounts/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(ApplicationUser userModel)
        {
            if (ModelState.IsValid)
            {
                bool userCheck = IsUserExists(userModel.UserName);
                if (userCheck == false)
                {
                    var user = new OnlineExam.Models.UserAccountModel.ApplicationUser();
                    user = userModel;
                    var result = await _userManager.CreateAsync(user, userModel.UserPassword);
                    if (result.Succeeded)
                    {
                        return Logout();
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("","Username already exist");
                }

            }
            return View(userModel);
        }

        // GET: UserAccounts/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var userAccount = await _context.ApplicationUser.FindAsync(id);
            if (userAccount == null)
            {
                return NotFound();
            }
            return View(userAccount);
        }

        // POST: UserAccounts/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("UserAccountId,UserName,UserPassword,UserFullName,UserGender,UserPriviledge,UserDesignation,UserDepartment,UserMailId,UserAddress,UserMobileNo,UserPhoto,UserQualification")] UserAccount userAccount)
        {
            if (id != userAccount.UserAccountId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userAccount);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserAccountExists(userAccount.UserAccountId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(userAccount);
        }

        // GET: UserAccounts/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var userAccount = await _context.ApplicationUser
                .FirstOrDefaultAsync(m => m.UserAccountId == id);
            if (userAccount == null)
            {
                return NotFound();
            }

            return View(userAccount);
        }

        // POST: UserAccounts/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var userAccount = await _context.ApplicationUser.FindAsync(id);
            _context.ApplicationUser.Remove(userAccount);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool UserAccountExists(int id)
        {
            return _context.ApplicationUser.Any(e => e.UserAccountId == id);
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(ApplicationUser login)
        {
            ///var user = new OnlineExam.Models.UserAccountModel.ApplicationUser { UserName = login.UserName };
            //TempData["user"] = user;
            var result = await _signInManager.PasswordSignInAsync(login.UserName, login.UserPassword, true, false);

            if (result.Succeeded)
            {
                 var userData = from x in _context.ApplicationUser.Where(x => x.UserName == login.UserName).ToList()
                                    select new { x.UserFullName, x.Email, x.UserAddress ,x.UserName
                                    ,x.UserPhoto ,x.UserMobileNo,x.UserGender,x.UserQualification,
                                    x.UserDepartment,x.UserDesignation,x.UserPriviledge,x.UserAccountId};

                //List<ApplicationUser> userList = new List<ApplicationUser>();
                foreach (var item in userData)
                {
                    userList.Add(new ApplicationUser 
                    { UserFullName =item.UserFullName, UserAccountId= item.UserAccountId,UserName=item.UserName,
                      Email=item.Email,UserDepartment=item.UserDepartment,UserGender=item.UserGender, 
                      UserPriviledge=item.UserPriviledge, UserPhoto=item.UserPhoto, UserAddress=item.UserAddress
                    });
                    //userList.Add(new ApplicationUserReplica { UserAccountId = item.UserAccountId });
                }
                //List<ApplicationUserReplica> userList= new List<ApplicationUserReplica>();
                //userList.Add(new ApplicationUserReplica { UserFullName = userData.Select(x => x.UserFullName).ToString()});
                // userList.Add(new ApplicationUserReplica { UserAccountId =Convert.ToInt32(userData.Select(x => x.UserAccountId)) });

                var sdata=JsonConvert.SerializeObject(userList);
                TempData["userData"] = sdata;
                return RedirectToAction(nameof(LoginInfo));
            }
            else
            {
                ModelState.AddModelError("", "Please enter you username and password correctly");
            }
            return View(login);
        }
        public  bool IsUserExists(string userName)
        {
            int c=_context.ApplicationUser.Where(x => x.UserName == userName).Count();
            if (c >= 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        [AllowAnonymous]
        public ActionResult Logout()
        {
            _signInManager.SignOutAsync();
            return RedirectToAction(nameof(Login));
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult LoginInfo()
        {
            userList=JsonConvert.DeserializeObject<List<ApplicationUser>>(TempData["userData"].ToString());
            TempData.Keep();
            foreach(var item in userList)
            {
                TempData["userId"] = item.UserAccountId;
            }
            return View();
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...