There are a number of ways to authenticate an angularJS application. This is the one I am currently using. It uses a FormsAuthentication cookie in the same way as a regular ASP.Net WebForms/MVC app would.
The structure is basically Web Api, a single MVC home controller with an Index.cshtml and angular.
publicclassAccountsController:ApiController{ [HttpPost]publicHttpResponseMessageSignIn(UserDataModeluser){if(this.ModelState.IsValid){// authenticate the user however you wish to do so here....if(authenticated){varresponse=this.Request.CreateResponse(HttpStatusCode.Created,true);FormsAuthentication.SetAuthCookie(user.UserName,false);returnresponse;}returnthis.Request.CreateErrorResponse(HttpStatusCode.Forbidden);}returnthis.Request.CreateErrorResponse(HttpStatusCode.BadRequest,this.ModelState);}}// USER DATAMODEL:publicclassUserDataModel{publicstringUserName{get;set;}publicstringPassword{get;set;}}
Which adds an encrypted cookie to the response.
So now we have a $rootScope.user object that has an authenticated property set to true/false. This allows us to hide/show menus, etc. Obviously this can be tampered with so we secure things by locking down any server side code we want to:
123456789
[Authorize]publicclassAccountsController:ApiController{ [HttpPost]publicHttpResponseMessageSomethingPrivate(){// this will only be reached if the FormsAuthentication cookie arrives in the request. The [Authorize] filter will redirect to a HTTP 403 Forbidden Request if none is present.}}
This will remove the FormsAuthentication cookie from the user’s browser. The angularjs $rootScope.user will be reset and we are now logged out.
The only other thing to be aware of is when the user refreshed the page, etc. We need to authomatically ‘sign in’ the user if the cookie is present. This is done on our MVC Controller that supplies the Index.cshtml page.