Securing ASP.NET Web APIs
Dominick Baier h p://leastprivilege.com @leastprivilege think mobile! Dominick Baier
• Security consultant at thinktecture • Focus on – security in distributed applica ons – iden ty management – access control – Windows/.NET security – mobile app security
• Microso MVP for Developer Security • ASP.NET Web API Advisor • [email protected] • h p://leastprivilege.com think mobile! @leastprivilege 2 Agenda
• HTTP security & SSL • ASP.NET Web API v2 architecture • Applica on scenarios
• (Token-based) authen ca on • Authoriza on • 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 authen ca on is required – Status code of 401 indicates unauthorized – WWW-Authen cate response header indicates preferred authen ca on method
Status Code: 401 unauthorized
WWW-Authen cate: Scheme realm="myapp"
@leastprivilege 6 Authen ca on for HTTP-based services • Creden als transmi ed (typically) via Authoriza on header • e.g. Basic authen ca on, access tokens… • some mes other means (query string, cookie…)
GET /service/resource
Authoriza on: scheme creden al
@leastprivilege 7 The Web API v2 Security Pipeline
Host Web API
OWIN/ MessageHandler Authen ca on Authoriza on Katana (global/per-route) Filter Filter
Host/Framework Web API cross-cu ng Web API specific independent concerns, Authoriza on concerns, e.g. CORS authen ca on e.g. authen ca on
h p://www.asp.net/vnext/overview/owin-and-katana/an-overview-of-project-katana
@leastprivilege 8 Katana Authen ca on 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 Authen ca on 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 Authoriza on filter
• Determines if a resource needs authen ca on – [AllowAnonymous] to skip authoriza on for an ac on – 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 authoriza on filter
• Derive from AuthorizeA ribute
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/Ac on-based Authoriza on
• Get rid of the ght coupling between applica on code and security requirements
[ResourceActionAuthorize("Update", "Customer")] public IHttpActionResult Put(Customer customer) { ... }
h p://thinktecture.github.com/Thinktecture.Iden tyModel/
@leastprivilege 13 Applica on Styles
• Same-Domain & Cross-Domain – classic vs modern
• Same Domain – Browser based applica ons – Web APIs and clients live in the same domain • AJAX style callbacks from server-rendered pages • SPA applica ons (like the built-in template in VS2012) – O en cookie based security • poten al CSRF problems
@leastprivilege 14 Same-Domain Scenario
• Web APIs inherit security se ngs of web host – e.g. cookies, Windows authen ca on, client certs...
Application
Login Web APIs Pages
$.ajax
@leastprivilege 15 CSRF – The Problem
Login, send authen ca on cookie get authen ca on cookie
h p://app.com h p://app.com/delete/5
Tab/Process Tab/Process
Browser
@leastprivilege 16 Web API v1 CSRF Protec on
• Part of the SPA template in MVC 4 (Update 2)
Server [ValidateH pAn ForgeryToken]
render page & post-back: web api call: an -forgery cookie cookie + hidden field cookie + header
Page
@leastprivilege 17 Web API v2 CSRF Protec on
• 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 Applica on Styles II
• Cross-Domain – Web APIs and clients live in different domains • na ve apps (desktop, mobile) • client side JavaScript code (browser) • Mul tude of scenarios – shared secret authen ca on – CORS restric ons for JavaScript-based clients – token-based authen ca on • built-in token endpoint • OAuth2 authoriza on server
@leastprivilege 19 Shared Secret Authen ca on
• HTTP Basic Authen ca on • Shared signature approaches (e.g. hawk)
GET /service/resource
Authoriza on: Basic base64(username:password)
@leastprivilege 20 An -pa ern!
• The client must store the secret or obtain it from the user (on every request) – storage must be done in clear text (or reversible encryp on) • Server has to validate the secret on every request – high computa onal cost due to brute force protec on
• The probability of accidental exposure of the secret is increased
@leastprivilege 21 Token-based Authen ca on
Token Service
request access token
Web APIs Bob use access token
@leastprivilege 22 OAuth2 (RFC 6749)
• Framework for reques ng and using access tokens for – na ve clients – web clients – browser-based clients
• OAuth2 introduces the concept of an Authoriza on Server – traffic cop between clients, users and services
@leastprivilege 23 Embedded Authoriza on Server
• e.g. Swap creden al with (long-lived) token
GET /service/token
GET /service/resource
Authoriza on: Bearer
@leastprivilege 24 Embedded Authoriza on Server (Katana View)
OWIN Host
Authorization Server MW User Agent
Bearer MW Application
@leastprivilege 25 Step 1a: Token Request
Resource Server Authoriza on 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 Authoriza on 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 Authoriza on 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 Authoriza on Server (Katana View)
Authoriza on Server (1)
User Agent (2) OWIN Host
JWT MW Applica on
1…n
@leastprivilege 30 AuthorizationServer & IdentityServer v3
h ps://github.com/thinktecture/Thinktecture.Authoriza onServer h ps://github.com/thinktecture/Thinktecture.Iden tyServer.v3
@leastprivilege 31 Separa ng user creden als from the client… • Local / mobile / user-agent based clients – Implicit Flow
• Server-based / confiden al clients – Autoriza on Code Flow
@leastprivilege 32 Implicit Flow (Na ve / Local Clients)
Resource Owner Client
@leastprivilege 33 Step 1a: Authoriza on Request
Resource Server Authoriza on 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: Authen ca on
@leastprivilege 35 Step 1c: Consent
@leastprivilege 36 Twi er Consent
@leastprivilege 37 Evernote Consent
@leastprivilege 38 The Consent Screen is important!
h p://zachholman.com/2011/01/oauth_will_murder_your_children/
@leastprivilege 39 Step 1d: Token Response
Resource Server Authoriza on Server
GET /cb# access_token=abc& expires_in=3600& state=123
Resource Owner Client
@leastprivilege 40 Summary – Implicit Flow
• User enters creden als at the authoriza on server – not at the client • authoriza on server returns (short lived) access token – to reduce exposure of token • O en combined with OS helper mechanisms – cookie container – na ve APIs
@leastprivilege 41 Excursion: CORS (Cross Origin Resource Sharing)
h p://server1/client.htm h p://server2/service
? $.ajax( ... ) Data
@leastprivilege 42 CORS Sample
OPTIONS /service
Access-Control-Request-Method: PUT Origin: h p://server1
$.ajax( ... ) Service Access-Control-Allow-Origin: h p://server1
PUT /service
@leastprivilege 43 CORS in Web API v2
Thinktecture.Iden tyModel.H p.Cors.WebApi
System.Web.Cors
[EnableCors("origin", "headers", "verbs")] public class CustomersController : ApiController { // actions... }
@leastprivilege 44 Authoriza on Code Flow (Server-based Clients)
Web Applica on Resource Server (Client)
Resource Owner
@leastprivilege 45 Step 1a: Authoriza on Request
Web Applica on Authoriza on Server (Client)
GET /authorize? client_id=webapp& scope=read& redirect_uri=https://webapp/cb& response_type=code& state=123
Resource Owner
@leastprivilege 46 Step 1d: Authoriza on Response
Web Applica on Authoriza on Server (Client)
GET /cb? code=xyz& state=123
Resource Owner
@leastprivilege 47 Step 2a: Token Request
Web Applica on Authoriza on Server (Client)
POST /token Authorization: Basic (client_id:secret)
grant_type=authorization_code& authorization_code=xyz
Resource Owner
@leastprivilege 48 Step 2b: Token Response
Web Applica on Authoriza on Server (Client)
{ "access_token" : "abc", "expires_in" : "3600", "token_type" : "Bearer", "refresh_token" : "xyz" }
Resource Owner
@leastprivilege 49 Step 3: Resource Access
Web Applica on Resource Server (Client)
GET /resource
Authorization: Bearer access_token
Resource Owner
@leastprivilege 50 (Step 3: Refreshing the Token)
Client Authoriza on Server
POST /token Authorization: Basic (client_id:secret)
grant_type=refresh_token& refresh_token=xyz
@leastprivilege 51 Refresh Token Management (Flickr)
@leastprivilege 52 Refresh Token Management (Dropbox)
@leastprivilege 53 Refresh Token Management (Microso Live)
@leastprivilege 54 Summary – Code Flow
• Designed for "confiden al" clients – client can store secret securely – client authen ca on and authoriza on based on client iden ty possible – typically server-based applica ons • Accountability is provided – access token never leaked to the browser • Long-lived access can be implemented
@leastprivilege 55 Summary
• HTTP has a very simple security model • Correct handling of SSL is paramount • Same- vs Cross-Origin applica ons
• Think about CSRF, CORS • Token based (and thus cookie-less) authen ca on is the way to go – separate client from API – embedded authoriza on server – full blown authoriza on server (product)
@leastprivilege 56