无效登录管理员角色ASP.NET MVC

时间:2016-11-19 22:52:53

标签: asp.net-mvc asp.net-mvc-5

我使用MVC 5种子用户和角色为管理员创建了一个角色。管理员角色已创建到数据库中。但是,每当我想登录时,我都会收到“无效登录尝试”。即使我为管理员插入了正确的电子邮件以及正确的密码!

MTC控制器:

namespace MTC.Controllers
{
    [Authorize]
    public class Check : Controller
    {
        private ApplicationDbContext Db = new ApplicationDbContext();


        public ActionResult Index()
        {
            return View();
        }

        // GET: Check
        public ActionResult Details()
        {
            var userId = User.Identity.GetUserId();
            var Account = Db.Checks.Single( x=> x.ApplicationUserId == userId);
            return View(Account);
        }


        //Only Admin authorised to access 
        [Authorize(Roles ="admin")]
        public ActionResult DetailsAdminOnly(int Userid)
        {
            var AdminCheck = Db.AccountChecks.Find();
            return View("Details", AdminCheck);
        }
        //Action for Admin to view Balance of users' accounts by passing the account ID 
        public ActionResult ViewAcounts()
        {
            return View(Db.AccountChecks.ToList());

        }

Configuration.cs

protected override void Seed(AutomatedTellerMachine.Models.ApplicationDbContext context)
{
    //Creating a user store and user amanger to access DB context from each 
    var userStr = new UserStore<ApplicationUser>(context);
    // specify user class
    var usermgr = new UserManager<ApplicationUser>(userStr);

    // Checking for existence Admin by email account
    if (!context.Users.Any(ad => ad.UserName == "admin@atmservice.co.uk"))
    { 
        //Declare username and Email
        var Newuser = new ApplicationUser {UserName = "admin", Email ="admin@atmservice.co.uk" };

        //Pass the validation
        usermgr.Create(Newuser, "Admin_12345678");

        var Checkingservice = new AccountService(context);
        Checkingservice.CheckingUsersAccount("admin","user", Newuser.Id, 1000);

        //Check for existing method using the name property
        context.Roles.AddOrUpdate(name => name.Name, new IdentityRole { Name = "admin" });
        context.SaveChanges();

        usermgr.AddToRole(Newuser.Id, "admin" );
    }

}

Login.cshtml

<h2>@ViewBag.Title.</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                <h4>Use a local account to log in.</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Log in" class="btn btn-default" />
                    </div>
                </div>
                <p>
                    @Html.ActionLink("Register as a new user", "Register")
                </p>
                @* Enable this once you have account confirmation enabled for password reset functionality
                    <p>
                        @Html.ActionLink("Forgot your password?", "ForgotPassword")
                    </p>*@
            }
        </section>
    </div>
    <div class="col-md-4">
        <section id="socialLoginForm">
            @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
        </section>
    </div>
</div>

这是登录操作方法

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }

        // 

0 个答案:

没有答案