WebAPI Basic Token Authentication (1) Generating Token Dummy Teaching

It is about to be used as an Android APP. The front and back ends are separated, and WebAPI must be written in the background to do the operation.

But the API can't be used by anyone, so we need to add authentication to filter illegal requests.

1. Create a project

 

 

 

2. Create AP controller

 

 

3. Start coding with nonsense for half a day (simple login to assign Token)

front desk code

  @using (Html.BeginForm("Index", "Default", FormMethod.Post))
    {
        <div>
            <input type="text" name="username" />
            <input type="text" name="pwd" />
            <input type="submit" value="登陆">

        </div>
    }

controller code

   [HttpPost]
        public ActionResult Index(string username, string pwd)
        {
            if (IsTrue(username, pwd))
            {
                //generate token
                // focus here
                //The namespace System.Web.Security parameter asks the version, cookie name, current time, end time, whether it continues to be a persistent cookie (True, False), data, cookie storage path
                System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(0, username, DateTime.Now,
                    DateTime.Now.AddHours(1), true, string.Format("{0}&{1}",
                    username, pwd), System.Web.Security.FormsAuthentication.FormsCookiePath);
                //encryption
                string ticketNum = System.Web.Security.FormsAuthentication.Encrypt(ticket);

                if (ticketNum != null && ticketNum.Trim().Length > 0)
                {
                    return RedirectToAction("Show", "Default", new { ticket = ticketNum });
                }
            }
            else
            {

            }
            return View();
        }

        public ActionResult Show(string ticket)
        {
            ViewBag.pp = ticket;
            return View();
        }

        public bool IsTrue(string name, string pwd)
        {
            if (name == "123" && pwd == "123")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

  

Display of the Show view

<body>
    Token:
    @ViewBag.pp
</body>

  

It is so simple that the generation of Token encryption is successful, and the actual usage will be written tomorrow~ If you do not accumulate steps, you will not be able to reach a thousand miles, and you will not be able to make a river without counting small streams~ 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325037886&siteId=291194637
Recommended