title: ASP Web API Bearer token Authentication using angular and ADFS3
body: <p><strong>tl;dr: Can get bearer token using angular from adfs, but cant authenticate on the webserver</strong></p>
  
  <p>For a new project we are implementing an api using asp.net web api 2 (.net 4.5.2) that is consumed by a javascript application (written in angular, but that does not matter). Our user accounts are stored in AD, which we would love to use.</p>
  
  <p>In our older applications, using mvc, it was easy to connect everything and access claims you specified in ADFS, using js however is proving to be difficult.</p>
  
  <p>Using the new endpoints in adfs 3, we can get the beaerer token using javascript (and a bit of web api):</p>
  
  <pre><code>GET https://path.to.sts/adfs/oauth2/authorize?parameters
  </code></pre>
  
  <p>Gives us a token that we pass on to our web api (otherwise the STS will block you due to CORS errors):</p>
  
  <pre><code>$scope.tokenRequest = {
             grant_type: "authorization_code",
             client_id: "client id thing",
             redirect_uri: "http://path.to.api/api/token",
             code: "Token from prev call"
  }
  
  $http({
      method:'POST',
      url: "https://kevin.local/app/test/token",
      data: $scope.tokenRequest,
      headers: {'Content-Type': 'text/json'}
  })
  .success(function(response){
      $cookies['token'] = response['access_token'];
  })
  </code></pre>
  
  <p>The call is:</p>
  
  <pre><code>public async Task&lt;IHttpActionResult&gt; Token(OAuthResquest request)
  {
      string accessToken = string.Empty;
      HttpClient client = new HttpClient();
  
      var postData = new List&lt;KeyValuePair&lt;string, string&gt;&gt;();
      postData.Add(new KeyValuePair&lt;string, string&gt;("grant_type", request.grant_type));
      postData.Add(new KeyValuePair&lt;string, string&gt;("code", request.code));
      postData.Add(new KeyValuePair&lt;string, string&gt;("client_id", request.client_id));
      postData.Add(new KeyValuePair&lt;string, string&gt;("redirect_uri", request.redirect_uri));
      HttpContent content = new FormUrlEncodedContent(postData);
      var response = (await client.PostAsync(new Uri
         ("https://path.to.sts/adfs/oauth2/token"), content));
  
      response.EnsureSuccessStatusCode();
      string result = null;
      if (response.IsSuccessStatusCode)
      {
          if (response.Content != null)
              result = (await response.Content.ReadAsStringAsync());
  
          obj = JsonConvert.DeserializeObject(result);
      }
      else
      {
          return StatusCode(response.StatusCode);
      }
  
      HttpContext.Current.Response.Cookies.Add(new HttpCookie("accessToken", result["accessToken"]));
      return Ok(obj);
  }
  </code></pre>
  
  <p>This gives us a bearer token. In angular I have an interceptor that adds this to each http request, which works, because I can see it in the inspector.</p>
  
  <p>Unfortunately, this is where I got stuck. I can't seem to find how to get authentication working, using adfs, given the bearer token:</p>
  
  <pre><code>$http.get("https://api.url/apo/call/to/auth/endpoint")
     .success(function (res) {
         console.log("mothafucking auth calls", res);
      })
  </code></pre>
  
  <p>In startup.cs I have:</p>
  
  <pre><code>public void Configuration(IAppBuilder appBuilder)
  {
      HttpConfiguration config = new HttpConfiguration();
      ConfigureAuth(appBuilder);
  
      WebApiConfig.Register(config);
      appBuilder.UseWebApi(config);       
  }
  </code></pre>
  
  <p>in startup.auth.cs we experimented with  <code>app.UseOAuthBearerToken</code>, <code>app.UseActiveDirectoryFederationServicesBearerAuthentication</code>, <code>app.UseOAuthBearerTokens(OAuthOptions)</code> and <code>app.UseOAuthBearerAuthentication</code>, but I keep getting 401's on api calls decorated with [Authorize], let alone access the claims we specified in adfs. </p>
  
  <pre><code>public void ConfigureAuth(IAppBuilder app)
  {
      app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
  
      //What middleware do we need to activate with what options?
      app.UseOAuthBearerTokens(options);
  
      app.UseActiveDirectoryFederationServicesBearerAuthentication(new Microsoft.Owin.Security.ActiveDirectory.ActiveDirectoryFederationServicesBearerAuthenticationOptions()
      {
          //What goes here?
       });
  }
  </code></pre>
  
  <p>The documentation for this use case seems to be severely lacking. We found examples for this, using local accounts (where a user has to register), using facebook or google, ..</p>
  
  <p>We could fix it if we put an MVC layer in betweeen all of this, but thats our worst case back up, we really want to be able to consume our api from javascript (or mobile for that matter).</p>
  
  <p>Thanks!</p>