Implement certification authorization in ANGULARJS applications

Source: Internet
Author: User
Tags sessionstorage

Implement certification authorization in ANGULARJS applications

In every serious application, authentication and authorization are a very important part. A single page app is no exception. The app does not expose all of the data and functionality to all users. Users need authentication and authorization to view a specific part of the app, or to perform specific behavior in the app. In order to identify the user in the app, we need to have the user sign in.

In terms of user management, traditional server-side applications and single-page applications are implemented differently, and single-page applications can communicate with the server in a way that is Ajax-only. This is also true for logins and exits.

The server side responsible for identifying the user needs to expose an authentication power outage. A single page application will send the user input information to this node for authentication. In a typical token based on an authentication system, this service is used to obtain a token or an object containing the name and role information of the logged-on user after the authentication is complete. The client needs to get the token in all the security APIs.

Since the behavior of acquiring TOEKN will occur more than once, we'd better have this token present on the client. In angular, we can put this value in a service because the service is a monomer in the client. However, if the user refreshes the page, the value in the service will be lost. In this case, it is best to store the value in a browser-provided secure store, where we use sessionstorage because it is automatically emptied when the browser is closed.

Implement Login

Let's look at some code now. Assuming that we have implemented all of the server-side logic and have a api/login login authentication called the rest interface, it will return a token. Let's write a simple service for user login. In the following we will gradually add functionality for this service:

App.factory ("Authenticationsvc", Function ($http, $q, $window) {  var userInfo;  function login (userName, password) {    var deferred = $q. Defer ();    $http. Post ("/api/login", {      username:username,      password:password    }). Then (function (result) {      UserInfo = {        AccessToken:result.data.access_token,        userName:result.data.userName      };      $window. sessionstorage["UserInfo"] = json.stringify (userInfo);      Deferred.resolve (UserInfo);    }, Function (Error) {      deferred.reject (error);    });    return deferred.promise;  }  return {    login:login  };});

In the actual code, you might want to refactor the stored code into a separate service. Here for the sake of simplicity, we just put it in a service he uses. This service can be used by a controller that handles the login function.

Secure routing

We need to set up some secure routes in the app. If a user is not logged in and wants to enter a secure route, he should be redirected to the login page. We can use the Routing option resolve to implement this function. The following code snippet shows one of the implementation ideas:

$routeProvider. When ("/", {  templateurl: "templates/home.html",  Controller: "HomeController",  Resolve: {    auth: ["$q", "Authenticationsvc", Function ($q, authenticationsvc) {      var userInfo = Authenticationsvc.getuserinfo ();      if (userInfo) {        return $q. When (UserInfo);      } else {        return $q. Reject ({authenticated:false});      }    ]  }});

resolveA block can contain multiple blocks of code that will return the Promise object when it is finished. To illustrate, the above code is auth not in the framework, but we define it ourselves. You can make changes according to your needs.

There are many reasons to pass or reject a route. In this case, you can pass an object when parsing/rejecting a promise. We have not implemented the method in the service yet getLoggedInUser() . It is a very simple way to return objects from the service loggedInUser .

App.factory ("Authenticationsvc", function () {  var userInfo;  function GetUserInfo () {    return userInfo;  }});

The promise sent through the above code will be broadcast via $rootscope. If the route is resolved, then the $routechangesuccess event will be broadcast. However, if the route fails, then event $toutechangeerror will be broadcast. We will listen for the $routechangeerror event and redirect the user to the login page. Because the event is at the $rootscope level, it is a good idea to run bind the event handler in the function.

App.run (["$rootScope", "$location", Function ($rootScope, $location) {  $rootScope. $on ("$routeChangeSuccess", function (userInfo) {    console.log (userInfo);  });  $rootScope. $on ("$routeChangeError", function (event, current, Previous, EVENTOBJ) {    if (eventobj.authenticated = = = False) {      $location. Path ("/login");});}  ]);

Handling page Refreshes

When the user refreshes the page, the service loses its existing state. We need to get the data from the session storage of the browser and assign the values to the Loggerinuser variable. Since a factory is only called once, we need to set the variable in an initialization function, as shown in the following code:

    function init () {      if ($window. sessionstorage["UserInfo"]) {        userInfo = Json.parse ($window. sessionstorage[" UserInfo "]);      }    } Init ();

Exit

When the user wants to exit from the app, the corresponding API must be called along with the token contained in the request header. Once the user exits, we also need to empty the data in the Sessionstorage. The following example contains an exit function that needs to be added to the authentication service.

function logout () {  var deferred = $q. Defer ();  $http ({    method: "POST",    Url:logouturl,    headers: {      "Access_token": Userinfo.accesstoken    }  }). Then (function (Result) {    $window. sessionstorage["UserInfo"] = null;    UserInfo = null;    Deferred.resolve (result);  }, Function (Error) {    deferred.reject (error);  });  return deferred.promise;}

Summarize

Authentication methods for single-page applications are very different from traditional Web applications. As the main work is moved to the browser side, the user's state also needs to be stored on the client. It is important to remember that the user's state also requires server-side saving and validation, because the hacker is likely to have the client steal the user's data.

This article is translated from implementing authentication in Angular applications, the original address http://www.sitepoint.com/ implementing-authentication-angular-applications/

Implement certification authorization in ANGULARJS applications

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.