Rights Management Learning one, ASP. NET Forms Authentication

Source: Internet
Author: User
Tags decrypt httpcontext send cookies ticket

Description: The VS2017 and MVC5 used in this sample.
System regardless of size, big or cock silk, generally inseparable from registration, login. Then we will analyze the user identity authentication.

Simple implementation of login, logoff

Before learning. NET when you do not know what forms of identity authentication, directly with the session to achieve login, the effect is fine. And the user information exists on the service side, security.
Front-End Code:

@if (String. Isnullorwhitespace (Viewbag.username)) {<Formaction="/home/login1" ><InputType="Text"Name="UserName"/><input type="Submit" value= "login"/> </form>}else{ <form  action="/HOME/LOGOUT1" > <div> Current user is logged in, login name: @ViewBag. UserName</div>  <input type= "submit" value= "exit"/> </form>}    

Background code:

Public ActionResultIndex () {Viewbag.username = session["UserName"]?. ToString ();return View ();}Publicvoid login1 ( string userName) {if (! String. Isnullorwhitespace (userName)) //in order to facilitate the demonstration, do not really verify Session[ " UserName "] = UserName; else session[ "userName"] = null; Response.Redirect (Request.UrlReferrer.LocalPath); //redirect to original page} public void logout1 ( "userName"] = Span class= "Hljs-keyword" >null; Response.Redirect (Request.UrlReferrer.LocalPath); //redirect to original page}            

is not, simple and clear. The ability to expand or customize what you want to do is very useful. But we need to maintain the session. For example, the system is republished, or IIS is automatically restarted. There will be a case where the session is lost. That is, the user will somehow improve the need to sign in again. The experience was very bad. (The session service and database are not discussed here first). Since Microsoft has a set of mature rights management, why don't we use it?

Forms Authentication Login, Logout

Start forms authentication in Web. config first:

<system.web>  <authentication mode="Forms"></authentication>

Background code:

public void login2 (string userName) {if (! String. Isnullorwhitespace (userName)) //in order to facilitate the demonstration, do not really verify the Formsauthentication.setauthcookie ( UserName, true); //login Response.Redirect (Request.UrlReferrer.LocalPath); //redirect to original page} public void logout2 () {formsauthentication.signout ();  Logout Response.Redirect (Request.UrlReferrer.LocalPath); //redirect to original page}            

Front Code:

@if (! request.isauthenticated) {<Formaction="/home/login2" ><InputType="Text"Name="UserName"/><input type=  "submit" value= "login"/> </form>}else{<form Span class= "hljs-attr" >action= "/home/logout2" > <div> Current user is logged in, login name: @Context. User.identity.name</ div> <input type= "submit" value=  "exit"/> </FORM>}     

Such a few lines of code enable our login and logoff. Unlike our own session management login. Forms authentication is the right to store information in a cookie to the browser. This method name can also be seen by SetAuthCookie. However, the cookie information is encrypted.
It is necessary to explain the relationship between the session and the cookie. When we use the session to maintain the user state, we actually use cookies.

However, forms authentication simply saves the information in a cookie and does not maintain a corresponding session on the server.
Don't believe you can test. You can log in two ways, and then clear the session can be measured. (How to clear the session? Restart IIS, or modify the background code under recompile access)
"description" Why does user authentication save cookies? Because HTTP is a stateless protocol. For the server, each request is the same. Therefore, the user can only be identified by each request with a cookie. (No other way for the time being considered)

Custom Identity Authentication

The login used above is simple, but the reality is often complicated. Clearly the normal business needs to save more user information. So can we extend the identity? The answer is yes.
Background code:

PublicvoidLogin3 (String userName) {if (!String. Isnullorwhitespace (UserName))For demonstration purposes, do not really validate {UserInfo user =New UserInfo () {Name = userName, logintime = DateTime.Now};1. Serialization of user information to be savedvar data = jsonconvert.serializeobject (user);2. Create a FormsAuthenticationTicket that contains the login name and additional user data. FormsAuthenticationTicket ticket =new FormsAuthenticationTicket (2, UserName, DateTime.Now, DateTime.Now.AddDays (1), true, data); //3, encrypt save string cookievalue = Formsauthentication.encrypt ( Ticket); //4. Create a login cookie based on the encryption result HttpCookie cookie = new HttpCookie ( Formsauthentication.formscookiename, Cookievalue); Cookies. HttpOnly = true; Secure = Formsauthentication.requiressl; Cookies. Domain = Formsauthentication.cookiedomain; Cookies. Path = Formsauthentication.formscookiepath; //5. Write a login cookie Response.Cookies.Remove (cookie. Name); RESPONSE.COOKIES.ADD (cookie); } Response.Redirect (Request.UrlReferrer.LocalPath); //redirect to original page}           

Then the Application_AuthenticateRequest method in Global.asax:

ProtectedvoidApplication_AuthenticateRequest () {GetUserInfo ();}Read user information to HttpContext.Current.User via Coolie decryptionPublicvoidGetUserInfo (){1. Read Login cookie HttpCookie cookie = request.cookies[formsauthentication.formscookiename];try {UserInfo UserData =null; //2. Decrypt cookie value, get FormsAuthenticationTicket object FormsAuthenticationTicket ticket = Formsauthentication.decrypt (cookies. Value); if (Ticket! = null &&  String. IsNullOrEmpty (ticket. UserData) = = false) //3. Restore User Data UserData = Jsonconvert.deserializeobject<userinfo> (ticket. UserData); if (Ticket! = null && userData! = null) //4. Construct our Myformsprincipal instance and give it back to the context. User assignment value. HttpContext.Current.User = new myformsprincipal<userinfo> (Ticket, userData);} Span class= "Hljs-keyword" >catch {/* have exceptions and do not throw them to prevent attackers from tempted. */ }}

Front-End Code:

@{Myformsprincipal<userinfo> user = Context.User as Myformsprincipal<userinfo>; if (user = = null) {<Formaction="/home/login3" ><InputType="Text"Name="UserName"/><InputType="Submit"Value= "login"/> </form>} else {<form action= "/ Home/logout2 "> <div> the current user is logged in, Login name: @Context. User.identity.name</div> <div> Current user is logged in, logon time: @user. Userdata.logintime</div> <input type= "submit"  Value= "exit"/> </form>}}   

In fact, the whole process FormsAuthentication.SetAuthCookie(userName, true); //登录 is equivalent. Just by expanding, we save the data we want to store.
The process is also relatively simple:

    • Construct the data to be stored
    • Serialization of
    • Putting serialized information into a FormsAuthenticationTicket object
    • Encrypt objects by Formsauthentication.encrypt
    • Send cookies to the browser

What's a bit more complicated here is decryption and assigning a value to the user HttpContext.Current.User = new MyFormsPrincipal<UserInfo>(ticket, userData); .
Myformsprincipal need to implement Interface Myformsprincipal

PublicClass myformsprincipal<tuserdata>: IPrincipal where Tuserdata:ClassNew () {Private IIdentity _identity;Private Tuserdata _userdata;Public Myformsprincipal (FormsAuthenticationTicket ticket, Tuserdata userData) {if (ticket = =NullThrownew ArgumentNullException ( "ticket"); if (userData = null) throw new ArgumentNullException ( "UserData"); _identity = new formsidentity (ticket); _userdata = UserData; } public tuserdata UserData {get { return _userdata; }} public IIdentity Identity {get { return _identity;} } public bool IsInRole (string role) //here temporarily does not implement {return false;}}   

There's nothing special about it, just passing in the ticket and customizing the data when you instantiate it.

Authorized

With the login is generally inseparable from authorization. Microsoft's things are good, it is generally complete sets of sets.

[Authorize]public ActionResult LoginOk(){    return View();}

Just add a authorize feature directly to the action, and the person will automatically check to see if they are logged in. If no sign-in automatically jumps to the login page. Login page settings or in Web. config

<system.web>  <authentication mode="Forms" > <forms loginUrl="/home/index"></forms>

This simple authorization verification is obviously not enough. Many times some pages are accessible only to certain people. such as VIP. Then we have to expand again.

 //inherit Authorizeattributepublic Span class= "Hljs-keyword" >class myauthorizeattribute:  authorizeattribute{public  Override void onauthorization ( AuthorizationContext filtercontext) {if (filterContext.HttpContext.User.Identity.Name!) =  "farm Code Life") {FilterContext.HttpContext.Response.Write ( " You are not a VIP user and cannot access confidential data "); FilterContext.HttpContext.Response.End (); return;} base. Onauthorization (Filtercontext); }} 
[MyAuthorize]public ActionResult LoginVIP(){    return View();}

Yes, it's that simple. Say so much, come to Zhang:

Recommended reading:

      • Http://www.cnblogs.com/fish-li/archive/2012/04/15/2450571.html
        Demo:
      • https://github.com/zhaopeiym/BlogDemoCode/tree/master/Rights Management/1-forms identity authentication
      • Https://www.cnblogs.com/zhaopei/p/authorize-1.html

Rights Management Learning one, ASP. NET Forms Authentication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.