AngularJS Authentication

4,131 views
Skip to first unread message

Jonathan Risch

unread,
Jul 5, 2013, 9:51:20 AM7/5/13
to ang...@googlegroups.com
Hello,

Angular noob here, I was wondering if someone can stir me towards the right direction regarding a site with restful API authentication.

I am building an one-page application that would require users to log in to access it. What I would like to achieve is to present the user a login form (separate view /#/login) when he's not logged in and run the username and password provided against an API that I have developed (c#). The user would enter his username and pass and I would submit (post/get) them to my api ( api/user/login ) and depending on the result, I assume I would need to create a session/cookie and store there the user object (user id, name etc.) that I return from the API.

From looking around a bit, I found several interesting posts like but I am still a bit unclear of the whole process. Some examples I found for starters, would lose the session the moment the user would refresh the page and he'd have to login again and other similar issues which I am afraid due to my limited knowledge of Angular, I still cannot fully grasp.

I was thinking of doing something similar to this: 

$rootScope.$on('$routeChangeStart', function(event, next, current) {
  if (!User.isAuthenticated() && next.templateUrl !== '/partials/login.html') {
    return $location.path("/login");
  }
});

Where User is a service that has api calls like login, isAuthenticated etc.

Those are my initial thoughts. Any suggestions would be greatly appreciated.

Thanks!

Kevin Sheppard

unread,
Jul 5, 2013, 10:48:46 AM7/5/13
to ang...@googlegroups.com
Here's a rough sketch of an authentication system using LocalStorage, Angular Factories and Angular Services:

var app = angular.module("login-app", []);

app.service("UserService", function($http, $location, user) {
 return {
  isAuthenticated: function() {
   return localStorage.getItem("authToken") != undefined;
  },

  getAuthToken: function() {
   return localStorage.getItem("authToken");
  },
 
  setUser: function(u) {
    user.user = u;
    localStorage.setItem("authToken", u.authToken);
  },
 
  endSession: function() {
    localStorage.removeItem("authToken");
    $location.path("/login");
  }
 }
});

app.factory("user", function() {
    return {
        user: {}
    }
});

app.controller("ApplicationCtrl", function($location, $scope, User, user) {
    if(!User.isAuthenticated()) {
        $location.path("/login");
    }

    $scope.user = user.user;
});

app.controller("LoginController", function($http, $location, $scope, UserService, user) {
    $scope.username;
    $scope.password;
    $scope.login = function() {
        $http.post(/*your url*/, {username: $scope.username, password: $scope.password}).then(function(data) {
            //Return an object that contains all user information including the user's ID/authentication token
            //and any other information that may be needed.
            UserService.setUser(data);
            $location.path("/index");
        }, function() {
            //Invalid Username or password notification
        })
    }
});

Grant Rettke

unread,
Jul 5, 2013, 11:29:18 PM7/5/13
to ang...@googlegroups.com
On Fri, Jul 5, 2013 at 8:51 AM, Jonathan Risch <unseen...@gmail.com> wrote:
> Angular noob here, I was wondering if someone can stir me towards the right
> direction regarding a site with restful API authentication.

https://github.com/fnakstad/angular-client-side-auth

Mauro Servienti

unread,
Jul 6, 2013, 2:31:13 AM7/6/13
to ang...@googlegroups.com

As far as I can tell from your post you are using Asp.Net WebAPI/MVC as the backend/server technology, I am in the exact same situation plus the fact that I’m using Windows Azure ACS as the authentication system (for that matters), I’ve setup my solution in the following manner:

 

-          I have enabled FormsAuthentication on the server (web.config);

-          Configured, in the web.config, a route (/security/signin) to be not secured, so everyone can reach it;

-          told to FormsAuth that the login page is “/security/signin”;

 

What happens when an anonymous users (no formsauth cookie) arrives is that asp.net redirects the user to /security/signin. I have setup 2 different AngularJS SPA, one just for authentication and one for the application.

 

Side-note: why 2? Because security concerns are important, having 2 completely different applications where moving from one to the other is controlled server side let me with the safety that a power user cannot mess up client side code with F12 browser tools and change the security behavior.

 

Now, you are an anonymous user and you are redirected in what I call the “acs.app”, one single page with one single view/controller whose role is just to allow the user to perform authentication, authentication is performed “server side” or via the Azure ACS, it is just not relevant to the SPA, the SPA simply sends credentials to the server and wait for an HTTP response, it the response is a redirect it honors it and if the server has set the Auth cookie everything works as expected on the client there is no need to determine if the user is authenticated or not, you just need to authorize the user but that is a different story.

Once the above is setup the browser at each “ajax” call to the WebAPI backend sends back all the cookies and thus you can use standard .net tools to determine on the server if the user is authenticated or not, and in the case he/she is not authenticated you simply returns the correct http response and the only role of the SPA is just to redirect to the login page (or do whatever you like to tell to the user that he/she is not authenticated).

 

.m

--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To post to this group, send email to
ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Peter Bacon Darwin

unread,
Jul 7, 2013, 3:01:16 AM7/7/13
to ang...@googlegroups.com
You can always take a look at angular-app and the associated book. It has auth built-in and all is explained in the chapter on Security
Pete

Witold Szczerba

unread,
Jul 7, 2013, 12:46:27 PM7/7/13
to ang...@googlegroups.com

Hi,
You can take a look at the:
http://witoldsz.github.io/angular-http-auth/

It is a working example of the concept described in detail, check the links on that page.

Of course, it does not persist sessions between page reloads (server-side is mocked in that app), but if your server uses cookies, the session will "survive".

Regards,
Witold Szczerba

--

Alex G.

unread,
Jul 8, 2013, 4:30:53 AM7/8/13
to ang...@googlegroups.com
Thanks for all the replies. Regarding the asp.net service i mentioned, I only expose a few REST services that I want to use with AngularJS. I cannot redirect to those services.

How could I make the session persist though? Do I need to set up a server on nodejs for example?

Thanks in advance.


--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/WXpabbN38kQ/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.

Peter Bacon Darwin

unread,
Jul 8, 2013, 6:53:45 AM7/8/13
to ang...@googlegroups.com
Look at angular-app.  It does exactly this!

Jonathan Risch

unread,
Jul 8, 2013, 7:04:14 AM7/8/13
to ang...@googlegroups.com
Hi Kevin,

Thanks for your reply. What is this "user" object that you're injecting to both the service and the controller?
Reply all
Reply to author
Forward
0 new messages