Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Securing ASP.NET Web API (NDC Oslo 2013)

Securing ASP.NET Web API (NDC Oslo 2013)

Dominick Baier

June 13, 2013
Tweet

More Decks by Dominick Baier

Other Decks in Programming

Transcript

  1. Securing  ASP.NET  Web  API   based  Architectures   Dominick  Baier

      h=p://leastprivilege.com   @leastprivilege   think mobile!
  2. 2   @leastprivilege   Dominick  Baier   •  Security  consultant

     at  thinktecture   •  Focus  on   –  security  in  distributed  applica9ons   –  iden9ty  management   –  access  control   –  Windows/.NET  security     •  MicrosoG  MVP  for  Developer  Security   •  ASP.NET  Web  API  Advisor   •  [email protected]   •  h=p://leastprivilege.com   think mobile!
  3. 3   @leastprivilege   Agenda   •  HTTP  security  &

     SSL   •  ASP.NET  Web  API  architecture   •  OWIN  hosNng  &  authenNcaNon  middleware   •  The  (new)  Web  API  pipeline   •  AnN-­‐CSRF   •  CORS   •  (Token-­‐based)  authenNcaNon   •  OAuth2  
  4. 4   @leastprivilege   The  big  picture   HTTPS  

    Host   ASP.NET  Web  API  
  5. 5   @leastprivilege   Developers  &  SSL  

  6. 6   @leastprivilege   Security  model  for  HTTP-­‐based   services

      •  Simple  model   –  HTTP  +  content  +  SSL   •  Whenever  authenNcaNon  is  required   –  Status  code  of  401  indicates  unauthorized   –  WWW-­‐Authen0cate  response  header  indicates  preferred   authen9ca9on  method   WWW-­‐AuthenNcate:  Scheme  realm="myapp"   Status  Code:  401  unauthorized  
  7. 7   @leastprivilege   Authen9ca9on  for  HTTP-­‐based   services  

    •  CredenNals  transmi=ed  (typically)  via  Authoriza.on   header   •  e.g.  Basic  authen9ca9on,  access  tokens…   •  some9mes  other  means  (query  string,  cookie…)   AuthorizaNon:  scheme  credenNal   GET  /service/resource  
  8. 8   @leastprivilege   Authen9ca9on  &  Authoriza9on   h=p://www.asp.net/web-­‐api/overview/security/authenNcaNon-­‐and-­‐authorizaNon-­‐in-­‐aspnet-­‐web-­‐api  

  9. 9   @leastprivilege   OWIN  Hos9ng   •  New  hosNng

     infrastructure  for  ASP.NET   –  SignalR,  Web  API   •  Other  frameworks  (will)  use  this  infrastructure  as  well   –  e.g.  NancyFX,  FubuMVC,  ServiceStack   •  Various  hosNng  opNons   –  IIS,  self-­‐hos9ng,  Mono   •  MicrosoG  will  build  all  new  authenNcaNon  modules  as   OWIN  middleware   –  JWT,  FormsAuth,  Twicer,  LiveID,  Google,  Facebook…   h=p://www.asp.net/vnext/overview/owin-­‐and-­‐katana/an-­‐overview-­‐of-­‐project-­‐katana  
  10. 10   @leastprivilege   The  new  Pipeline   Host  

    Web  API   OWIN   MessageHandler   (global/per-­‐route)   AuthenNcaNon   Filter   AuthorizaNon   Filter   Host/Framework   independent  concerns,     e.g.  authen9ca9on   Web  API  cross-­‐cueng   concerns,  e.g.  CORS   Web  API  specific   authen9ca9on   Authoriza9on  
  11. 11   @leastprivilege   OWIN  Middleware   •  Global  

    public  class  AuthenticationMiddleware   {          private  readonly  Func<IDictionary<string,  object>,  Task>  _next;              public  AuthenticationMiddleware(Func<IDictionary<string,  object>,  Task>  next)          {                  _next  =  next;          }              public  async  Task  Invoke(IDictionary<string,  object>  env)          {                  //  inspect  env  and  do  credential  validation,  then  set  principal                    env["server.User"]  =  CreatePrincipal();                  await  _next(env);          }   }  
  12. 12   @leastprivilege   MessageHandler   •  Web  API,  global

     or  per-­‐route   public  class  MyHandler  :  DelegatingHandler   {          protected  async  override  Task<HttpResponseMessage>  SendAsync(              HttpRequestMessage  request,  CancellationToken  cancellationToken)          {                  //  inspect  request                      var  response  =  await  base.SendAsync(request,  cancellationToken);                    //  inspect  response                  return  response;          }   }  
  13. 13   @leastprivilege   Thinktecture  Authen9ca9onHandler   hcp://thinktecture.github.com/Thinktecture.Iden9tyModel.45/   AuthenticationHandler

    : DelegatingHandler Header Query String Client Certificate Cookie incoming  credenNal   mapping  credenNal   to  token  handler   1.  AuthenNcaNon   2.  Claims  TransformaNon   3.  (Session  handling)   4.  Set  Thread.CurrentPrincipal  
  14. 14   @leastprivilege   Authen9ca9on  filter   h=p://aspnetwebstack.codeplex.com/SourceControl/latest   [MySpecialAuthenticationMethod]

      public  class  CustomersController  :  ApiController   {          //  actions...   }  
  15. 15   @leastprivilege   Authoriza9on  filter   •  Determines  if

     a  resource  needs  authenNcaNon   –  [AllowAnonymous]  to  skip  authoriza9on  for  an  ac9on   –  emits  the  401  status  code,  if  unsuccessful   //  minimum  requirement  is  successful  authentication   [Authorize]   public  DataController  :  ApiController   {          [AllowAnonymous]          public  Data  Get()            {  …  }            [Authorize(Role  =  "Foo")]          public  HttpResponseMessage  Delete(int  id)          {  …  }   }  
  16. 16   @leastprivilege   Custom  authoriza9on  filter   •  Derive

     from  AuthorizeA1ribute   –  decorate  controller  and  ac9ons   public  class  PremiumUsersOnlyAttribute  :  AuthorizeAttribute   {          protected  override  bool  IsAuthorized(HttpActionContext  context)          {                  ClaimsPrincipal  client  =  ClaimsPrincipal.Current;                    //  custom  authorization  logic          }              protected  override  void  HandleUnauthorizedRequest(              HttpActionContext  actionContext)          {                  //  custom  response          }   }  
  17. 17   @leastprivilege   Claims-­‐based  Authoriza9on   •  Get  rid

     of  the  Nght  coupling  between  applicaNon  code   and  security  requirements   –  use  .NET  4.5  ClaimsAuthoriza0onManager  to  encapsulate   authoriza9on  policy   [ClaimsAuthorize("Update",  "Customer")]   public  Customer  Put()   {  ...  }  
  18. 18   @leastprivilege   Applica9on/Client  types   •  Same-­‐Domain  &

     Cross-­‐Domain   •  Same  Domain   –  Web  APIs  and  clients  live  in  the  same  domain   •  AJAX  style  callbacks  from  server-­‐rendered  pages   •  simpler  SPA  applica9ons  (like  the  built-­‐in  template)   –  Ohen  cookie  based  security   •  poten9al  CSRF  problems  
  19. 19   @leastprivilege   Application Login Same-­‐Domain  Scenario   • 

    Web  APIs  inherit  security  sebngs  of  web  host   –  e.g.  cookies,  Windows  authen9ca9on,  client  certs...   Pages Web APIs $.ajax  
  20. 20   @leastprivilege   CSRF  –  The  Problem   Browser

      Tab/Process   Tab/Process   Login,   get  authen9ca9on  cookie   h=p://app.com   h=p://app.com/delete/5   send  authen9ca9on  cookie  
  21. 21   @leastprivilege   ASP.NET  CSRF  Protec9on   •  Part

     of  the  SPA  template  in  MVC  4  (Update  2)   Server   [ValidateHcpAn9ForgeryToken]   render  page  &     an9-­‐forgery  cookie   <form>    <input  type="hidden"  value="anti-­‐forgery  token"  />   </form>     <script>…</script>   post-­‐back:   cookie  +  hidden  field   Page   web  api  call:   cookie  +  header  
  22. 22   @leastprivilege   Applica9on/Client  types   •  Cross-­‐Domain  

    –  Web  APIs  and  clients  live  in  different  domains   •  na9ve  apps  (desktop,  mobile)   •  client  side  JavaScript  code  (browser)   •  MulNtude  of  scenarios   –  shared  secret  authen9ca9on   –  CORS  restric9ons  for  JavaScript-­‐based  clients   –  token-­‐based  authen9ca9on   •  built-­‐in  token  endpoint   •  OAuth2  authoriza9on  server  
  23. 23   @leastprivilege   Shared  Secret  Authen9ca9on   •  HTTP

     Basic  AuthenNcaNon   •  Shared  signature  approaches  (e.g.  hawk)   AuthorizaNon:        Basic  base64(username:password)   GET  /service/resource  
  24. 24   @leastprivilege   Token-­‐based  Authen9ca9on    Client   Web

     API   Security   Token   Service   1.   Request  token   2.  Send  token    Token    Authorization:  Bearer  <token>  
  25. 25   @leastprivilege   Embedded  Token  Endpoint   •  Swap

     credenNal  with  (long-­‐lived)  token   AuthorizaNon:        Basic  base64(username:password)   GET  /service/token   <token>   GET  /service/resource   AuthorizaNon:          Bearer  <token>  
  26. 26   @leastprivilege   CORS   (Cross  Origin  Resource  Sharing)

      h=p://server1/client.htm   $.ajax(  ...  )   h=p://server2/service   ?   Data  
  27. 27   @leastprivilege   CORS  Sample   $.ajax(  ...  )

      Service   OPTIONS  /service     Access-­‐Control-­‐Request-­‐Method:  POST   Origin:  hcp://server1   Access-­‐Control-­‐Allow-­‐Origin:  hcp://server1   POST  /service  
  28. 28   @leastprivilege   CORS  in  Web  API  v2  

    Thinktecture.Iden9tyModel.Hcp.Cors.WebApi   System.Web.Cors   [EnableCors("origin",  "headers",  "verbs")]   public  class  CustomersController  :  ApiController   {          //  actions...   }  
  29. 29   @leastprivilege   Scenario:  API  Backend  &  many  Clients

      Web  API   AuthorizaNon  Server   1   2  
  30. 30   @leastprivilege   OAuth2   •  Framework  that  describes

     how  to  orchestrate  access   token  requests  and  usage   –  for  various  client  types   •  AuthorizaNon  server  component  factors  out   –  client  management   –  user  authen9ca9on  &  consent   –  coarse  grained  authoriza9on  
  31. 31   @leastprivilege   OAuth2  Applica9on  Architecture   ApplicaNon  

    AuthorizaNon  Server   Scopes:  read,  write,     delete,  search…   client_id=client1,   scope=search  read   access  token   access  token   {        "iss":  "myAuthzServer",        "aud":  "applicaNon",        "exp":  192990121,        "sub":  "Bob",        "client_id":  "client1",        "scope":  [  "search",  "read"  ]   }   Bob  
  32. 32   @leastprivilege   Announcing…   h=ps://github.com/thinktecture/Thinktecture.AuthorizaNonServer   AuthorizationServer

  33. 33   @leastprivilege   Summary   •  HTTP  has  a

     very  simple  security  model   •  Correct  handling  of  SSL  is  paramount   •  Same-­‐  vs  Cross-­‐Origin  applicaNons   •  Think  about  CSRF,  CORS   •  Token  based  (and  thus  cookie-­‐less)  authenNcaNon  is  the   way  to  go   –  embedded  issuer   –  full  blown  authoriza9on  server