Detailed explanation of login and authentication in angular development _angularjs

Source: Internet
Author: User
Tags md5 hash sessionstorage

Objective

Since angular is a single-page application, the majority of the resources will be loaded into the browser at the outset, so it is more necessary to pay attention to the timing of validation and ensure that only authenticated users can see the corresponding interface.

The authentication in this article refers to how to determine whether a user has logged in and to ensure that the authentication requirements of the server are met in every communication with the server. Note that it does not include a judgment as to whether a particular permission is specified.

For landing, mainly accept user's username password input , submit to the server for authentication , process Validation response , build authentication data on the browser side .

Two ways to implement authentication

Currently, there are two major categories of authentication methods:

Cookies

Traditional browser Web pages, are using Cookies to verify identity, in fact, the browser-side application layer, basically do not have to go to the authentication of things, Cookies set up by the server, in the submission of the request, the browser automatically append the corresponding Cookies information, so in In JavaScript code, you don't need to write specialized code for this. But every time you ask for it, you bring all the cookie data,

With the application of CDN, the gradual rise of the mobile end, Cookies are increasingly unable to meet the complex, multiple domain authentication requirements.

Secret key

In fact, the authentication based on the key is not a recent rise, it has been, even longer than the cookie history. When the browser requests the server, the key is appended to the request in a specific way, such as on the requested head (headers). To do this, you need to write specialized client-side code to manage.

The most recent JSON-based Web key standard is the (JSON Web Token) typical authentication using a key.

In WEB applications, if you are constructing an API, you should prioritize the use of key methods.

Processing Landing

Login is the first step of authentication, by landing, you can organize the corresponding authentication data.

Do you need to use a separate landing page?

Landing page processing, there are two ways:

A separate landing page , after landing completed, jump to a single page application, so that you can access the resources of a single page to control, to prevent access to non-logon users, suitable for the background or management tools of the application scene. But actually reduces the user experience of single page applications
landing within a single page application , which is more in line with the design concept of a single page application, more suitable for the mass product scene, because malicious people always get your single page application of the front-end Code

A separate landing page

In general, the purpose of using a separate landing page is to protect a page that is not accessed by anonymous users after landing. Therefore, in the landing page, the construction of a form, directly using the traditional method of recognition (non-Ajax), the back-end to verify the user name password successfully, the output after landing the single page of HTML application.

In this case, you can put the authentication information directly in the output HTML, for example, you can use Jade to construct a page like this:

<!--dashboard.jade-->
doctype HTML
HTML
 head
  link (rel= "stylesheet", href= "/assets/") App.e1c2c6ea9350869264da10de799dced1.css ")
 body
  script.
   Window.token =! {json.stringify (token)};
  Div.md-padding (Ui-view)
  script (src= "/assets/app.84b1e53df1b4b23171da.js")


After the user name password authentication succeeds, the backend can render the output HTML in the following way:

Return Res.render (' dashboard ', {
 token:token
});

Angular when a startup is applied, traffic that requires authentication is available. It also ensures that only successful users can enter this page.

Single-page application-Logged organization

For angular applications of multiple views, routing is generally used, within the page, there is generally a fixed sidebar menu, or the top navigation menu, the body area by the routing module to control.

The following example code uses angular Material to organize the page, and the routing module uses Ui-router. When the application is opened, there is a special loading animation, after loading, the display of the page, the use of AppController this controller, for no landing users, will show the landing form, landing completed, the page is divided into three parts, one is the top of the bread crumbs navigation , The second is the sidebar menu , the other is the main body of the routing control .

The code is as follows:

<body ng-app= "app" layout= "Row" >
 <div id= "Loading" >
  <!--page loading tips-->
 </div>
 <div Flex layout= "Row" Ng-cloak ng-controller= "AppController" ng-init= "Load ()" >
  <div ng-if= "! Isuserauth ", ng-controller=" Logincontroller ">
   <!--landing form-->
  </div>
  <div ng-if=" Isuserauth "Flex layout=" Row ">
   <md-sidenav flex=" md-is-locked-open= "true" class= "Stop-text-select Bbmd-sidebar MD-WHITEFRAME-4DP ">
    <!--sidebar menu-->
   </md-sidenav>
   <md-content Flex layout= "column" role= "main" >
    <md-toolbar class= "Stop-text-select md-whiteframe-glow-z1" >
     <! --top Menu-->
    </md-toolbar>
    <md-content>
     <!--routing-->
     <div ui-view class= " Md-padding "></div>
    </md-content>
   </md-content>
  </div>
 </div >
</body>

For Loading animations, it is AppController outside and can be AppController hidden in the code. This achieves the purpose of Loading disappearing after all css/javascript loads have been completed.

AppController There is a variable in isUserAuth initialization, false when the local stored session information validation is valid, or after the landing is completed, this value will be set ture , because ng-if of the control, you can realize the hidden landing form, display the purpose of the application content. It is important to note that the first thing to do is to delete and add a DOM element only if it is used instead of the first, and that it is only a ng-if ng-show/ng-hide matter of modifying the CSS properties of a DOM element, and that it is only then possible to ensure that after the login is completed, the contents of the single page application are The controller code in the current route executes directly.

Why the client also wants to encrypt the password

A more desirable login process based on username and password is this:

1. Browser-side to get the user input password, using a MD5 hash algorithm to generate a fixed length of the new password, such as md5(username + md5(md5(password))) , and then the password hash value and user name submitted to the backend

2. The backend according to the user name to obtain the corresponding salt, using user name and password hash value, calculate a ciphertext, according to user name and ciphertext to the database query

3. If the query succeeds, generate the key, return to the browser, and perform step 4th

4. The back-end generates the new salt, generates new ciphertext according to the new salt and the password hash value submitted by the browser. Update Salt and redaction in the database

There may be 80% of people who do not understand why it is so complicated to make a landing. This may have to be written in a special article to explain clearly. Let's explain why the browser side will hash the password for the following reasons:

1. Protect the user's password from the source to ensure that only the key record can get the user's original password
2. Even if the network is eavesdropping, and does not use HTTPS, then the stolen password, but also only after the hash, the maximum impact on the user's data in this server, without affecting the use of the same password other sites
3. Even the owner of the server is unable to obtain the user's original password
In this way, the greatest risk to the user is that the data in the current application is stolen. will not expand the scope of loss, there will never be the problem of CSDN.

Notice of successful landing

For some applications, not all pages require users to log in, may be some operation, only need to log in. In this case, the entire application must be notified after the login has been completed. This can be used to broadcast this feature.

The simple code is as follows:

Angular
 . Module (' app ')
 . Controller (' Logincontroller ', [' $rootScope ', Logincontroller]);

function Logincontroller ($rootScope) {
 //
 afterloginsuccess () {$rootScope after successful login
  . Broadcast (' User.login.success ', {
   //data required for transfer
  });
 }

In other controllers, you can listen to the broadcast and perform what you need to do after the login is successful, such as getting a list or details:

$scope. $on (' user.login.success ', function (handle, data) {
 //processing
});

Authentication information

After the login is successful, the server returns the key, and subsequent API requests require the key to be brought in, and the response to the request return needs to be checked for errors that are not valid for identity information. This series of work is more cumbersome, should be automatic completion of the line.

Save

There are probably several ways to save a key:

1.Cookies: As mentioned earlier, this is not recommended for use. At the same time, it also has the maximum 4k limit

2.sessionStorage:The tab page is valid, once closed, or a new tab is opened, Sessionstorage is not shared

3.localStorage: The ideal storage mode, unless the browser data is cleaned, otherwise localstorage stored data will always exist

4.Angular single case Service: stored in the application, the data will be lost after the refresh, of course, can not be shared between the tab page
The better approach is that the authentication information is stored in the Localstorage, but is initialized to the angular Service when the application is started.

To include authentication information in a request

The purpose of authentication information is to identify the server and get the data. Therefore, additional authentication information is required in the request.

In general applications, authentication information is placed in the headers header of the request. If you set headers on each request, it's too time-consuming and laborious. An interceptor is provided in the angular $httpProvider interceptors , which enables the uniform processing of each request and response.

The way to add interceptors is as follows:

Angular
 . Module (' app ')
 . config ([' $httpProvider ', function ($httpProvider) {
  $ HttpProvider.interceptors.push (Httpinterceptor);
 }];

HttpInterceptorare defined in the following ways:

Angular
 . Module (' app ')
 . Factory (' Httpinterceptor ', [' $q ', Httpinterceptor]);

function Httpinterceptor ($q) {return
 {
  //request issued before, can be used to add various authentication information
  request:function (config) {
   if ( Localstorage.token) {
    config.headers.token = Localstorage.token;
   }
   return config;
  },
  //Request Error
  Requesterror:function (err) {return
   $q. Reject (err);
  Successfully returned response
  Response:function (res) {return
   res
  },
  //returned response error, including a non-200 HTTP status code
  set when back-end response was returned Responseerror:function (Err) {return
   $q. Reject (Err);
  }
 ;
}

Interceptors provide full lifecycle processing of requests to return responses, which can generally be used to do the following things:

1. Unified add data in the sent request, such as adding authentication information

2. Unified processing errors, including errors when the request is made (such as the browser-side network is not available) and the error returned when responding

3. Unified processing of the response, such as caching some data, etc.

4. Show Request progress bar

In the example code above, when localStorage token This value is included, a value is added to the head of each request token .

Failure and treatment

Generally, the backend should set the token HTTP status code of the response to 401 when validation fails, so that it responseError can be handled uniformly in the interceptor:

Responseerror:function (err) {
 if ( -1 = = Err.status) {//
  remote server unresponsive
 } else if (401 = = err.status) {
  //401 Errors are generally used for authentication failures, depending on the error thrown by the backend on authentication failure
 } else if (404 = = Err.status) {
  //server returned 404
 } return
 $q. Reject (err);
}

Summarize

In fact, as long as the server returned the status code is not 200, will be called responseError , you can here, unified processing and display errors.

The above content is about angular development and application of the login and authentication related knowledge, hope to learn angular help.

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.