简体   繁体   中英

How to customize ASP.NET MVC Login Authentication?

I refer to this answer [Click Here] (the highest vote)

I just follow its direction but it didn't work to me.

The reason I need to create a customized login because I already have the database for my password and other verification for user access. I only need is to authenticate this user to use the module.

Any idea you have is valuable to me. Thank you.

UPDATE:

[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;
        }
    }

您正在寻找的是Custom AuthorizationAttribute ,请在此处检查

At last I've solve the problem. I found out something like this in my web.config

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

Then I comment out the modules then everything is going right.

And it will become like this.

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

This is auto generated in MVC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM