I want to create an example for authentication and authorization in an SPA angularjs application using asp.net mvc webapi as the backend and client side routing (no cshtml). Below is just example of functions that can be used to set up the complete example. But I just canĀ“t put it all togehter. Any help appreciated.
Questions:
- What is best practise: Cookie or Token based?
- How do I create the bearer token in angular to authorize on each request?
- Validation on API functions?
- How do I preserve the autentication signed in user on the client?
Example code:
Sign in form
<form name="form" novalidate> <input type="text" ng-model="user.userName" /> <input type="password" ng-model="user.password" /> <input type="submit" value="Sign In" data-ng-click="signin(user)"> </form>
Authentication Angular Controller
$scope.signin = function (user) { $http.post(uri + 'account/signin', user) .success(function (data, status, headers, config) { user.authenticated = true; $rootScope.user = user; $location.path('/'); }) .error(function (data, status, headers, config) { alert(JSON.stringify(data)); user.authenticated = false; $rootScope.user = {}; }); };
My API backend API Code.
[HttpPost] public HttpResponseMessage SignIn(UserDataModel user) { //FormsAuthetication is just an example. Can I use OWIN Context to create a session and cookies or should I just use tokens for authentication on each request? How do I preserve the autentication signed in user on the client? if (this.ModelState.IsValid) { if (true) //perform authentication against db etc. { var response = this.Request.CreateResponse(HttpStatusCode.Created, true); FormsAuthentication.SetAuthCookie(user.UserName, false); return response; } return this.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid username or password"); } return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState); }
Authorization Using the JWT library for restricting content.
config.MessageHandlers.Add(new JsonWebTokenValidationHandler { Audience = "123", SymmetricKey = "456" });
My API methods
[Authorize] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }