asp.net Authentication: Forms Authentication

Keywords: ASP.NET

Abstract:

Tomorrow will be New Year's Eve, idle is also idle, specially summarized some methods of authorization authentication under. net.

 

Forms authentication schematic

Forms authentication is form authentication, which needs to provide identity id and password for authentication and authorization management.

It should be a familiar one, just contacted. net may learn this thing.

Here's how he works:

 

Second, the picture is too boring. I have prepared a demo.

  

 

Because the default home page is IndexController/Index, this page only needs one line of "Index".

Design sketch:

OK, the page does not do any permission control, the display is normal.

 

Next, take a look at Default Controller/Index

using System.Web.Mvc;

namespace Forms.Controllers
{
    public class DefaultController : Controller
    {
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
    }
}

  

Access: http://localhost:12463/default

Obviously there is no permission to view, because we set permission authentication.

[Authorize]
public ActionResult Index()

 

Normally the production environment does not allow direct display of this 401 error

If the user has no login credentials, we will ask the user to return to the login page to complete the authentication operation.

Forms authentication supports setting login addresses in web.config

 

Okay, let's try again: http://localhost:12463/default

Jump to the authentication page as scheduled! Click login to jump back to http://localhost:12463/default if authentication is successful

Let's look at login's background processing logic

        public ActionResult Index()
        {
            var returnUrl = Request["ReturnUrl"];

            if (Request.HttpMethod == "POST")
            {
                var userid = Request["userid"];
                var password = Request["password"];

                if (userid == "123456" && password == "123456")
                {
                    var ticket = new FormsAuthenticationTicket(
                        1,
                        userid,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        true,
                        "role1,role2,role3",
                        "/"
                    );

                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    cookie.HttpOnly = true;
                    HttpContext.Response.Cookies.Add(cookie);

                    return Redirect(returnUrl);
                }
            }

            ViewBag.ReturnUrl = returnUrl;

            return View();
        }

  

  

 

All right, I wish to show you! So far, simple privilege authentication has been completed.

 

3. Adding Role Functions

The front is only a simple login authentication, if the project requires the authentication granularity of permission is fine, it can not be satisfied.

For example: IndexNeedRole 4 is only open to one role 4

[MyAuthorize(Roles = "role4")]
public ActionResult IndexNeedRole4()
{
    return View();
}

 

We need to create a new Authorize feature for validating roles and user names: MyAuthorize

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            var ticket = FormsAuthentication.Decrypt(cookie.Value);
            var roles = ticket.UserData;

            var inRoles = false;
            foreach (var role in roles.Split(','))
            {
                if (Roles.Contains(role))
                {
                    inRoles = true;
                    break;
                }
            }

            return inRoles;
        }
    }

  

Now that the code is ready, let's try again: http://localhost:12463/default/IndexNeedRole4

Back to normal, back to the privilege authentication interface.

Click login and find that the page is just refreshed. All input s are empty.

This is normal because the ticket role in login/index login only assigns "role1,role2,role3"

Plus role4

        public ActionResult Index()
        {
            var returnUrl = Request["ReturnUrl"];

            if (Request.HttpMethod == "POST")
            {
                var userid = Request["userid"];
                var password = Request["password"];

                if (userid == "123456" && password == "123456")
                {
                    var ticket = new FormsAuthenticationTicket(
                        1,
                        userid,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        true,
                        "role1,role2,role3,role4",
                        "/"
                    );

                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    cookie.HttpOnly = true;
                    HttpContext.Response.Cookies.Add(cookie);

                    return Redirect(returnUrl);
                }
            }

            ViewBag.ReturnUrl = returnUrl;

            return View();
        }

  

Click login again

OK, normal as scheduled

Posted by Mutley on Thu, 21 Mar 2019 12:09:53 -0700