2

I am using Custome users Account which look like The Model: USer

public class user
    {
        [Key]
        public int userid { get; set; }


        [Required]

        [StringLength(150)]
        [DisplayName("Email")]
        public string Email { get; set; }
        [DisplayName("Password")]
        [Required]
        [DataType(DataType.Password)]
        [StringLength(20, MinimumLength = 6)]
        public string Password { get; set; }
        public string PasswordSalt { get; set; }
    }

The Controller:

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

        [HttpGet]
        public ActionResult logIn()
        {
            return View();
        }

        [HttpPost]
         public ActionResult logIn(Models.user user)
        {
            if (ModelState.IsValid)
            {
                if (user !=null)
                {
                    FormsAuthentication.SetAuthCookie(user.Email, false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Login Data is Incorrect.");
                }
            }
            return View(user);
        }


        [HttpGet]
        public ActionResult Registration()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Registration(Models.user user)
        {
            if (ModelState.IsValid)
            {

                var sysUser = db.users.Create();

                sysUser.Email = user.Email;
                sysUser.Password = user.Password;


                db.users.Add(sysUser);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");

            }

        else
    {
        ModelState.AddModelError("","Login Data is Incorrect.");

    }
               return View();

    }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index","home");
        }

The Login.CSHTML (View)

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Login Failed. Check your Details.");
   <div>
   <fieldset>
   <legend>Login Form</legend>
   <div>@Html.LabelFor(u=>u.Email)</div>

   <div>@Html.TextBoxFor(u=> u.Email)
   @Html.ValidationMessageFor(u=>u.Email)
   </div>

   <div>@Html.LabelFor(u=>u.Password)</div>

   <div>@Html.PasswordFor(u=> u.Password)
   @Html.ValidationMessageFor(u=>u.Password)
   </div>

   <input type ="submit" Value="Login" />
   </fieldset>
   </div> 
   }

This is working code : I want to make an administrator and some users ... I want to make protected some pages for users ...

  • Use the SimpleMembership or your own membership provider. Then you can use action or controller attributes like `[Authorize(Roles="Admin")]`. Take a look at http://www.codeproject.com/Articles/689801/Understanding-and-Using-Simple-Membership-Provider or with a custom authorize: http://stackoverflow.com/questions/13264496/asp-net-mvc-4-custom-authorize-attribute-with-permission-codes-without-roles – devqon Apr 30 '14 at 07:59
  • Your users log in successfully if they type an email address and any password? What's the point in that? – Ant P Apr 30 '14 at 08:03
  • You can implement custom `Authorization` and use `[Authorize]` attribute as @user3153169 said. This way you can restrict the pages from unauthorized access. You can place this attribute on individual actions or entire controller. – Nilesh Apr 30 '14 at 08:08
  • @AntP Actually I have many users I want to make some protected pages for specific users – Beginer Programer Apr 30 '14 at 08:23
  • @BeginerProgramer I know. My point is that your `logIn` method doesn't validate that the user enters the correct password - only that they enter *any* password. – Ant P Apr 30 '14 at 08:32
  • @BeginerProgramer, Please check my answer and comment... – Krishnraj Rana Apr 30 '14 at 09:52

2 Answers2

0

You can achieve this functionality by implementing CustomAuthentication by inheriting AuthorizeAttribute class. This will restrict access to an action method or an entire controller. There are 2 main method you need to override which is - AuthorizeCore() and HandleUnauthorizedRequest()

For exa. Here i have defined one class let say - CustomAuthentication which checks user have rights or not to access.

public class CustomAuthentication : AuthorizeAttribute
    {
        private bool isAuthorized { get; set; }

        /// <summary>
        /// This function will return true if user authenticated user else return false
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            try
            {
                isAuthorized = true;

                if (!CheckUserLogin()) // This function check the user rights 
                {
                    isAuthorized = false;
                }

                return isAuthorized;

            }
            catch (Exception)
            {
                isAuthorized = false;
                return isAuthorized;
            }
        }

    /// <summary>
    /// If user is not authorize user then redirect it to Login page
    /// </summary>
    /// <param name="filterContext"></param>
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        try
        {
            string controllerName = filterContext.RouteData.GetRequiredString("controller").ToLower();
            string actionName = filterContext.RouteData.GetRequiredString("action").ToLower();


            if (!isAuthorized)
            {
                // if the request is AJAX return JSON else view.
                if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                {
                    filterContext.Result = new JavaScriptResult { Script = "redirectToLogin()" };
                }
                else
                {
                    RouteValueDictionary objCollect = filterContext.RouteData.Values;
                    string strRedirect = string.Empty;

                    // This logic is to construct the returnURL, you can ignore this part
                    for (int i = 2; i < objCollect.Count; i++)
                    {
                        strRedirect += objCollect.Keys.ElementAt(i) + "=" + Convert.ToString(objCollect.Values.ElementAt(i)) + "&"; 
                    }

                    var objQrystr = filterContext.HttpContext.Request.QueryString;
                    // Get the query-string and append it to URL
                    for (int i = 0; i < objQrystr.Count; i++)
                    {
                        strRedirect += objQrystr.GetKey(i) + "=" + Convert.ToString(objQrystr[i]) + "&"; 
                    }

                    if (!string.IsNullOrEmpty(strRedirect))
                    {
                        strRedirect = "?" + strRedirect.TrimEnd('&');
                    }
                   // End of Logic of constructing the returnURL

                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "LogOn", returnUrl = "/" + controllerName + "/" + actionName + strRedirect}));
                }
            }

        }
        catch (Exception)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "LogOn" }));
            return;
        }

    }

Now you have to decorate your controller or action with this custom attribute. like this -

[CustomAuthenticate()]
public class MyShopingController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Apart from the above example - you can also get the reference from this blog.

Krishnraj Rana
  • 6,516
  • 2
  • 29
  • 36
0

Create a custom action filter to handle your authorization requirements. Please check below links

http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-custom-action-filters http://www.codeproject.com/Articles/650240/A-Simple-Action-Filter-Overview

Hope this helps, DSR

DSR
  • 4,588
  • 29
  • 28