title: AngularJS clientside routing and token authentication with webapi
body: <p>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.</p>
  
  <p>Questions:</p>
  
  <ol>
  <li>What is best practise: Cookie or Token based?</li>
  <li>How do I create the bearer token in angular to authorize on each request?</li>
  <li>Validation on API functions?</li>
  <li>How do I preserve the autentication signed in user on the client?</li>
  </ol>
  
  <p>Example code: </p>
  
  <ol>
  <li><p>Sign in form</p>
  
  <pre><code>&lt;form name="form" novalidate&gt;
   &lt;input type="text" ng-model="user.userName" /&gt;
   &lt;input type="password" ng-model="user.password" /&gt;
   &lt;input type="submit" value="Sign In" data-ng-click="signin(user)"&gt;
  &lt;/form&gt;
  </code></pre></li>
  <li><p>Authentication Angular Controller</p>
  
  <pre><code>$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 = {};
      });
  };
  </code></pre></li>
  <li><p>My API backend API Code.</p>
  
  <pre><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);
  }
  </code></pre></li>
  <li><p>Authorization
  Using the JWT library for restricting content.</p>
  
  <pre><code>config.MessageHandlers.Add(new JsonWebTokenValidationHandler
  {
    Audience = "123",
    SymmetricKey = "456"
  });
  </code></pre></li>
  <li><p>My API methods</p>
  
  <pre><code>[Authorize]
  public IEnumerable&lt;string&gt; Get()
  {
   return new string[] { "value1", "value2" };
  }
  </code></pre></li>
  </ol>