如何自定义ASP.NET MVC登录身份验证?

时间:2015-05-13 10:27:13

标签: c# asp.net-mvc

我指的是这个答案[Click Here](最高票)

我只是遵循它的方向,但它对我不起作用。

我需要创建自定义登录的原因是因为我已经拥有了我的密码数据库和其他用户访问验证。我只需要验证此用户是否使用该模块。

你有任何想法对我有价值。谢谢。

更新

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            //Verify Username & Password Here
            string fullName = string.Empty;
            string userRole = string.Empty;
            string userId = string.Empty;
            userId = _usersRepository.GetUserId(model.Username, model.Password, ref fullName, ref userRole);
            if(!string.IsNullOrEmpty(userId))
            {
                if(_usersRepository.GetUserAccess(userId, userRole))
                {
                    UserProfile _userProfile = new UserProfile();
                    _userProfile.FullName = fullName;
                    _userProfile.UserId = userId;
                    _userProfile.Role = userRole;

                    //This portion will grant user authentication
                    SessionContext context = new SessionContext();
                    context.SetAuthenticationToken(fullName, false, _userProfile);
                    //FormsAuthentication.SetAuthCookie(userId, false);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "You don't have access to this system.");
                    return View(model);
                }
            }
            else
            {
                ModelState.AddModelError("", "Username or Password is Invalid.");
                return View(model);
            }

            return View(model);
        }

SessionContext.cs

public class SessionContext
    {
        public void SetAuthenticationToken(string name, bool isPersistant,UserProfile userData)
        {
            string data = null;
            if (userData != null)
                data = new JavaScriptSerializer().Serialize(userData);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddDays(1), isPersistant, userData.UserId.ToString());
            string cookieData = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieData)
            {
                HttpOnly = true,
                Expires = ticket.Expiration
            };

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        public UserProfile GetUserData()
        {
            UserProfile userData = null;

            try
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                    userData = new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(UserProfile)) as UserProfile;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return userData;
        }
    }

2 个答案:

答案 0 :(得分:0)

您要找的是自定义AuthorizationAttribute,请检查here

答案 1 :(得分:0)

最后我解决了这个问题。我在web.config

中发现了类似的内容
 <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>

然后我评论modules然后一切正常。

它会变成这样。

<system.webServer>
   <!-- <modules>
      <remove name="FormsAuthentication" />
    </modules> -->
  </system.webServer>

这是在MVC

中自动生成的