mvc5中的登录身份验证

时间:2020-04-17 16:28:25

标签: c# asp.net-mvc entity-framework asp.net-identity

在我的应用中,我通常有3个用户(管理员,客户和驱动程序),并且在默认页面中,我想添加一些新的导航栏,例如仅对特定用户可用。而当我这样做时,我会在不尝试验证用户身份的情况下显示那些导航栏(运行我的应用程序后,它会立即显示在默认页面中)。 这是我在默认控制器中的登录操作:

       [HttpGet]
        public ActionResult Login(LoginModel login)
        {
            HttpCookie cookie = Request.Cookies["Login"];
            if (cookie != null)
            {
                login.UserName = cookie.Values[0];
                login.Password = cookie.Values[1];
            }

            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginModel login, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
                var authManager = HttpContext.GetOwinContext().Authentication;
                IdentityUser user = await userManager.FindAsync(login.UserName, login.Password);
                if (user != null)
                {
                    var ident = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);
                    //I have 3 roles in my app
                    if (userManager.IsInRole(user.Id, "Customer"))
                    {
                        return Redirect(returnUrl ?? Url.Action("Index", "Riders"));
                    }
                    else if (userManager.IsInRole(user.Id, "Driver"))
                    {
                        return Redirect(returnUrl ?? Url.Action("Index", "Drivers"));
                    }
                    else if (userManager.IsInRole(user.Id, "Admin"))
                    {
                        return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
                    }
                    ViewBag.Message = string.Format("User {0} Login Successfully", user.UserName);
                }
            }
            //if remember me was checked 
            if (login.RememberMe == true)
            {

                Response.Cookies["Login"]["UserName"] = login.UserName;
                Response.Cookies["Login"]["Password"] = login.Password;
                Response.Cookies["Login"].Expires = DateTime.Now.AddYears(1);
            }
            ModelState.AddModelError("", "Invalid username or password");
            return View(login);
}

和我的共享文件夹包含:管理员部分视图+登录部分视图和其他一些共享视图 我在默认文件夹中也有一个登录视图。 这是我的管理员局部视图:

@using Microsoft.AspNet.Identity;
@using Microsoft.AspNet.Identity.EntityFramework;
@using Microsoft.Owin.Security;
@using Microsoft.Owin.Security.OAuth;
@using RidesApp.Models



@if (Request.IsAuthenticated)
{
    RidesDbContext context = new RidesDbContext();
    UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(context);
    UserManager<IdentityUser, string> userManager = new UserManager<IdentityUser, string>(userStore);


    bool exist = userManager.IsInRole(User.Identity.GetUserId(), "Admin");

    if (exist)
    {
        <ul class="navbar-nav ">    
            <li class="nav-item">
                @Html.ActionLink("Admin page", "Index", "Admin", new { @class = "nav-link" })
            </li>
        </ul>
    }

}

在部分登录视图中,我希望在用户登录后将登录链接更改为注销,但这也不起作用:

@using Microsoft.AspNet.Identity.EntityFramework;
@using Microsoft.AspNet.Identity.Owin;
@using Microsoft.Owin.Logging;
@using Microsoft.AspNet.Identity;
@using System.Web.Security;




@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOut", "Default", FormMethod.Post, new { id = "logoutForm" }))
    {
        @Html.AntiForgeryToken()

       <ul class="navbar-nav">
           <li>
               <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                   My Account
               </a>
           </li>

       </ul>

    }
}
else
{
    <ul class="navbar-nav ml-auto">
        <li class="nav-item ">
            @Html.ActionLink("Sign Up", "AddUser", "Admin", routeValues: null, htmlAttributes: new { id = ""})
            <i class="fa fa-user"></i>
        </li>

        <li class="nav-item">
            @Html.ActionLink("Login", "Login", "Default", routeValues: null, htmlAttributes: new { id = " " })
            <i class="fa fa-login"></i>
        </li>
    </ul>
}

在主布局页面中,在用户登录后,我具有以下生成新的导航栏的地方:

             @Html.Partial("_LoginPartial")
                @Html.Partial("_AdminPartial")
                <ul class="navbar-nav  ml-auto">
                    <li class="nav-item">
                        @Html.ActionLink("my profile", "Index", "Riders")
                    </li>
                </ul>

            </div>
        </div>

    </nav>


    <div>
        @RenderBody()
    </div>



</body>
</html>

但是,我看到的所有导航栏都没有登录。

最后,我的注销操作如下所示:

[Authorize]
        [HttpPost]
        public ActionResult LogOut()
        {
            /*  FormsAuthentication.SignOut();
              Session.Abandon();

              return RedirectToAction("Index");*/
            var authenticationManager = Request.GetOwinContext().Authentication;
            authenticationManager.SignOut();
            ViewBag.Message = "Logout Successfully";
            return RedirectToAction("Login");
        }

我错过了什么吗?我会感谢您的帮助。我正在使用实体框架(不是核心)。 谢谢你。

0 个答案:

没有答案