Securing ASP.NET Web Apis

Securing ASP.NET Web Apis

Securing ASP.NET Web APIs Dominick Baier hp://leastprivilege.com @leastprivilege think mobile! Dominick Baier • Security consultant at thinktecture • Focus on – security in distributed applicaons – iden9ty management – access control – Windows/.NET security – mobile app security • MicrosoF MVP for Developer Security • ASP.NET Web API Advisor • [email protected] • hp://leastprivilege.com think mobile! @leastprivilege 2 Agenda • HTTP security & SSL • ASP.NET Web API v2 architecture • ApplicaNon scenarios • (Token-based) authenNcaNon • AuthorizaNon • CSRF • CORS • OAuth2 @leastprivilege 3 ASP.NET Web API: the big picture Host ASP.NET Web API HTTPS @leastprivilege 4 Developers & SSL @leastprivilege 5 Security model for HTTP-based services • Simple model – HTTP + content + SSL • Whenever authencaon is required – Status code of 401 indicates unauthorized – WWW-Authen0cate response Header indicates preferred authen9caon method Status Code: 401 unauthorized WWW-AuthenNcate: Scheme realm="myapp" @leastprivilege 6 Authen9caon for HTTP-based services • Credenals transmied (typically) via Authoriza.on header • e.g. Basic authen9caon, access tokens… • some9mes other means (query string, cookie…) GET /service/resource AuthorizaNon: scheme credenal @leastprivilege 7 THe Web API v2 Security Pipeline Host Web API OWIN/ MessageHandler AuthenNcaNon AuthorizaNon Katana (global/per-route) Filter Filter Host/Framework Web API cross-cung Web API specific independent concerns, Authorizaon concerns, e.g. CORS authen9caon e.g. authen9caon hp://www.asp.net/vnext/overview/owin-and-katana/an-overview-of-project-katana @leastprivilege 8 Katana Authen9caon Middleware public class Startup { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies", // more options }); app.UseGoogleAuthentication(new GoogleAuthenticationOptions { AuthenticationType = "Google", // more options }); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AuthenticationType = "Bearer" // more options }); } } @leastprivilege 9 Authen9caon filter WebApiConfig.cs config.Filters.Add(new HostAuthenticationFilter("Bearer")); [HostAuthentication("Bearer")] public class TestController : ApiController { [HostAuthentication("Google")] public HttpResponseMessage Get() { } [OverrideAuthentication] [HostAuthentication("Cookies")] public HttpResponseMessage Delete() { } } @leastprivilege 10 Authorizaon filter • Determines if a resource needs authencaon – [AllowAnonymous] to skip authorizaon 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) { … } } @leastprivilege 11 Custom authorizaon filter • Derive from AuthorizeAribute public class PremiumUsersOnlyAttribute : AuthorizeAttribute { protected override bool IsAuthorized(HttpActionContext context) { var principal = actionContext .ControllerContext .RequestContext .Principal as ClaimsPrincipal; // custom authorization logic } protected override void HandleUnauthorizedRequest( HttpActionContext actionContext) { // custom response } } @leastprivilege 12 Resource/Ac9on-based Authorizaon • Get rid of the ght coupling between applicaon code and security requirements [ResourceActionAuthorize("Update", "Customer")] public IHttpActionResult Put(Customer customer) { ... } hp://thinktecture.github.com/Thinktecture.IdenNtyModel/ @leastprivilege 13 Applicaon Styles • Same-Domain & Cross-Domain – classic vs modern • Same Domain – Browser based applicaons – Web APIs and clients live in the same domain • AJAX style callbacks from server-rendered pages • SPA applicaons (like the built-in template in VS2012) – Ogen cookie based security • poten9al CSRF problems @leastprivilege 14 Same-Domain Scenario • Web APIs inherit security sengs of web host – e.g. cookies, Windows authen9caon, client certs... Application Login Web APIs Pages $.ajax @leastprivilege 15 CSRF – THe Problem Login, send authen9caon cookie get authen9caon cookie hp://app.com hp://app.com/delete/5 Tab/Process Tab/Process Browser @leastprivilege 16 Web API v1 CSRF Protec9on • Part of the SPA template in MVC 4 (Update 2) Server [ValidateHpAn9ForgeryToken] render page & post-back: web api call: an9-forgery cookie cookie + Hidden field cookie + Header Page <form> <input type="hidden" value="anti-forgery token" /> </form> <script>…</script> @leastprivilege 17 Web API v2 CSRF Protec9on • No cookies allowed anymore… // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter( OAuthDefaults.AuthenticationType)); WebApiConfig.cs @leastprivilege 18 Applicaon Styles II • Cross-Domain – Web APIs and clients live in different domains • nave apps (desktop, mobile) • client side JavaScript code (browser) • MulNtude of scenarios – sHared secret authen9caon – CORS restric9ons for JavaScript-based clients – token-based authen9caon • built-in token endpoint • OAuth2 authorizaon server @leastprivilege 19 SHared Secret Authen9caon • HTTP Basic AuthenNcaNon • Shared signature approaches (e.g. hawk) GET /service/resource AuthorizaNon: Basic base64(username:password) @leastprivilege 20 An9-paern! • The client must store the secret or obtain it from the user (on every request) – storage must be done in clear text (or reversible encryp9on) • Server has to validate the secret on every request – HigH computaonal cost due to brute force protec9on • The probability of accidental exposure of the secret is increased @leastprivilege 21 Token-based Authen9caon Token Service request access token Web APIs Bob use access token @leastprivilege 22 OAuth2 (RFC 6749) • Framework for requesNng and using access tokens for – nave clients – web clients – browser-based clients • OAuth2 introduces the concept of an AuthorizaNon Server – traffic cop between clients, users and services @leastprivilege 23 Embedded Authorizaon Server • e.g. Swap credenal with (long-lived) token GET /service/token <token> GET /service/resource AuthorizaNon: Bearer <token> @leastprivilege 24 Embedded Authorizaon Server (Katana View) OWIN Host Authorization Server MW User Agent Bearer MW Application @leastprivilege 25 Step 1a: Token Request Resource Server Authorizaon Server POST /token Authorization: Basic (client_id:secret) grant_type=password& scope=resource& user_name=owner& password=password& Resource Owner Client @leastprivilege 26 Step 1b: Token Response Resource Server Authorizaon Server { "access_token" : "abc", "expires_in" : "3600", "token_type" : "Bearer", "refresh_token" : "xyz" } Resource Owner Client @leastprivilege 27 More advanced scenarios client_id=client1, scope=searcH read AuthorizaNon Server access token APIs access token Bob { "iss": "myAuthzServer", "aud": "resources", "exp": 192990121, "sub": "Bob", Scopes: read, write, "client_id": "client1", delete, searcH… "scope": [ "search", "read" ] } @leastprivilege 28 JSON Web Token (JWT) Header { "typ": "JWT", "alg": "HS256" } Claims { "iss": "http://myIssuer", "exp": "1340819380", "aud": "http://myResource", "sub": "alice", "client_id": "xyz", "scope": ["read", "search"] } eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMD.4MTkzODAsDQogImh0dHA6Ly9leGFt Header Claims Signature @leastprivilege 29 External Authorizaon Server (Katana View) AuthorizaNon Server (1) User Agent (2) OWIN Host JWT MW Applicaon 1…n @leastprivilege 30 AuthorizationServer & IdentityServer v3 hps://github.com/thinktecture/Thinktecture.AuthorizaNonServer hps://github.com/thinktecture/Thinktecture.IdenNtyServer.v3 @leastprivilege 31 Separang user creden9als from the client… • Local / mobile / user-agent based clients – Implicit Flow • Server-based / confidenal clients – Autorizaon Code Flow @leastprivilege 32 Implicit Flow (Nave / Local Clients) Resource Owner Client @leastprivilege 33 Step 1a: Authorizaon Request Resource Server Authorizaon Server GET /authorize? client_id=nativeapp& scope=read& redirect_uri=http://localhost/cb& response_type=token& state=123 Resource Owner Client @leastprivilege 34 Step 1b: Authen9caon @leastprivilege 35 Step 1c: Consent @leastprivilege 36 Twijer Consent @leastprivilege 37 Evernote Consent @leastprivilege 38 THe Consent Screen is important! hp://zachholman.com/2011/01/oauth_will_murder_your_children/ @leastprivilege 39 Step 1d: Token Response Resource Server Authorizaon Server GET /cb# access_token=abc& expires_in=3600& state=123 Resource Owner Client @leastprivilege 40 Summary – Implicit Flow • User enters credenals at the authorizaon server – not at the client • authorizaNon server returns (short lived) access token – to reduce exposure of token • Oen combined with OS helper mechanisms – cookie container – nave APIs @leastprivilege 41 Excursion: CORS (Cross Origin Resource SHaring) hp://server1/client.htm hp://server2/service ? $.ajax( ... ) Data @leastprivilege 42 CORS Sample OPTIONS /service Access-Control-Request-Method: PUT Origin: hp://server1 $.ajax( ... ) Service Access-Control-Allow-Origin: Hjp://server1 PUT /service @leastprivilege 43 CORS in Web API v2 THinktecture.Iden9tyModel.Hp.Cors.WebApi System.Web.Cors [EnableCors("origin", "headers", "verbs")] public class CustomersController : ApiController { // actions... } @leastprivilege 44 Authorizaon Code Flow (Server-based Clients) Web Applicaon Resource Server (Client) Resource Owner @leastprivilege 45 Step 1a: Authorizaon

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    56 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us