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

Secure Your REST API

Stormpath
December 01, 2016

Secure Your REST API

Sign up for Stormpath: https://api.stormpath.com/register
More from Stormpath: https://stormpath.com/blog

Les Hazlewood, Stormpath CTO, already showed you how to build a Beautiful REST+JSON API, but how do you secure your API? At Stormpath, we spent 18 months researching best practices. Join Les as he explains how to secure your REST API, the right way. We'll also host a live Q&A session at the end.

Les will cover:
OAuth2
OAuth Access Tokens
Scoping for Permissions
JWTs
Using JWTs as tokens
Securing JWTs
Authentication, Authorization, and More!

Stormpath

December 01, 2016
Tweet

More Decks by Stormpath

Other Decks in Technology

Transcript

  1. REST API Security Les Hazlewood @lhazlewood PMC Chair, Apache Shiro

    Expert Group Member, JEE Application Security (JSR-375) Founder & CTO, Stormpath
  2. About Stormpath • User Management API for Developers • Password

    security • Authentication and Authorization • Multi Tenancy • MFA, SAML, OAuth2 • LDAP & Active Directory Cloud Sync • Instant-on, scalable, and highly available • Free for developers ...
  3. Overview • HTTP Authentication • HTTP Authentication Schemes Comparison •

    API Key Authentication • Token Authentication • Authorization
  4. REST API Focus • Eliminate server state • Secure user

    credentials • Secure server endpoints • Expose access control rules • SPAs and Mobile: ‘Untrusted Clients’
  5. HTTP Authentication & Authorization • Authorization header • No Custom

    Headers! • Stay spec-standard • No pre-flight CORS requests (browsers) req’d • Custom schemes easily supported
  6. HTTP Basic String value = username + ‘:’ + raw_password

    String schemeValue = base64_encode(value) ... GET /admin HTTP/1.1 Authorization: Basic schemeValue
  7. HTTP Basic Pros: • Very easy to use • Supported

    by everything Cons: • Raw password always transmitted • Easy to leak raw password if not careful (logging) • Susceptible to Man-In-The-Middle attacks • HTTPS *always* required • Client must constantly retain/reference the raw password (server clients usually ok, browser clients not ok)
  8. Digest Schemes: Client request.headers[‘Client-Id’] = getMyId() String digest = hmacSha256(request,

    password) request.headers[‘Authorization’] = ‘Foo ‘ + digest send(request)
  9. Digest Schemes: Server String clientId = request.headers[‘Client-Id’] byte[] password =

    lookupPassword(clientId); String serverComputedDigest = hmacSha256(request, password) String val = request.headers[‘Authorization’] String clientSpecifiedDigest = val.remove(‘Foo ‘) if (clientSpecifiedDigest != serverComputedDigest) { sendError(401, response) return } //otherwise request is authenticated
  10. Digest Schemes: OAuth 1.0a example Authorization: OAuth realm="http://sp.example.com/", oauth_consumer_key="0685bd9184jfhq22”, oauth_token="ad180jjd733klru7",

    oauth_signature_method="HMAC-SHA1", oauth_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D", oauth_timestamp="137131200", oauth_nonce="4572616e48616d6d65724c61686176”
  11. Digest Schemes Pros: • Probably most secure • Password never

    sent over the wire • HTTPS not required (but your data may still require HTTPS) • Can guarantee end-to-end HTTP message authenticity (HTTPS cannot do this) • Not susceptible to Man-In-The-Middle attacks Cons: • Very difficult to design safely • Difficult to understand and use • Difficult to implement libraries • Client needs to retain a constant reference to the password (server clients usually ok, browser clients maybe not?)
  12. Bearer Token Schemes opaque-token can be whatever you want* *should

    always be cryptographically-signed and expire
  13. Bearer Token Schemes Pros: • Easier to use than digest

    • De-facto standard token format (JWT) • Can contain state – no server sessions needed • Does not require constant access to the user password Cons: • HTTPS always required, during and always after login (not a big deal nowadays) • Cannot guarantee end-to-end HTTP message authenticity (like digest schemes can) • Susceptible to Man-In-The-Middle attacks • Token creation and renewal workflows can be very complicated and confusing depending on use case (OAuth2 confuses many people). • When used for Browser or Mobile, additional security still required (Origin checks, CSRF- protection, etc) • Token content is not standard – applications can open themselves to attack
  14. Bearer Token Schemes: Session IDs? Session ID cookies are a

    type of bearer token! Set-Cookie: session=dhj7Wkx8fj; secure; HttpOnly Notes: - Same ‘Cons’ as previous slide - Require server state L - Susceptible to CSRF attacks L - Opaque – no meaning for rich clients (SPA, mobile) L - Service Architectures might need a centralized ID de-referencing service L - Can set the secure and HttpOnly flags J - JWTs are better, as we’ll soon see.
  15. Custom Scheme • Only if you really, Really, REALLY know

    what you’re doing. Seriously. No, rly. Srsly. • Non-standard, so you essentially must provide your own client libraries.
  16. Custom Scheme • Stormpath has a custom SAUTHC1 digest scheme

    • Authenticates the entire HTTP Message, including the Body (OAuth 1.0a does not) • Uses nonces to prevent replay attacks • Uses key derivation algorithms and HMAC-SHA-256 • We use it for our own SDKs* • If you’re curious: https://github.com/stormpath (search for ‘sauthc1’ in any stormpath-sdk-* project) *Basic still supported for non-SDK clients or ‘weird’ environments
  17. API Keys • Entropy • Password Independent • Scope •

    Speed • Limited Exposure • Traceability
  18. API Keys • Can be thought of as a really

    long username and password pair. • Can be used with any HTTP Authentication Scheme that accepts a username and password: Basic, Digest, OAuth2, etc. • Almost exclusively used for server-to-server communication. • Never embed API Key secrets in untrusted clients like JavaScript or mobile applications.
  19. HTTP Basic with API Key String value = apiKeyId +

    ‘:’ + apiKeySecret String schemeValue = base64_encode(value) ... GET /admin HTTP/1.1 Authorization: Basic schemeValue
  20. Session ID Problems • They’re opaque and have no meaning

    themselves (they’re just ‘pointers’). • Service-oriented architectures might need a centralized ID de-referencing service
  21. Session ID Problems • Opaque IDs mean clients can’t inspect

    them and find out what it is allowed to do or not - it needs to make more requests for this information. • Susceptible to CSRF attacks
  22. Session ID Problems • Sessions = Server State! • You

    need to store that state somewhere • Session ID à look up server state on *every request*. • Really not good for distributed/clustered apps • Really not good for scale
  23. 1. Token Request POST /token HTTP/1.1 Origin: https://foo.com Content-Type: application/x-www-form-urlencoded

    grant_type=password&username=username&password=password *Assert allowed origin for browser-based apps
  24. 2. Token Response HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store

    Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", “token_type":"example", “expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value” }
  25. Example: Token Request using an API Key POST /token HTTP/1.1

    Content-Type: application/x-www-form-urlencoded grant_type=client_credentials&client_id=apiKeyId&client_secret=apiKeyS ecret *Assert allowed origin for browser-based apps
  26. JSON Web Tokens (JWT) • A URL-safe, compact, self-contained string

    with meaningful information that is usually digitally signed or encrypted. • The string is ‘opaque’ and can be used as a ‘token’. • Many OAuth2 implementations use JWTs as OAuth2 Access Tokens.
  27. JSON Web Tokens (JWT) • You can store them in

    cookies! But all those cookie security rules still apply (CSRF protection, etc). • You can entirely replace your session ID with a JWT.
  28. JSON Web Tokens (JWT) In the wild they look like

    just another ugly string: eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJ pc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQo gImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnV lfQ.dBjftJeZ4CVPmB92K27uhbUJU1p1r_wW1gFWFOEj Xk
  29. JSON Web Tokens (JWT) But they do have a three

    part structure. Each part is a Base64Url-encoded string: eyJ0eXAiOiJKV1QiLA0KICJhb GciOiJIUzI1NiJ9 . eyJpc3MiOiJqb2UiLA0KICJle HAiOjEzMDA4MTkzODAsDQogIm h0dHA6Ly9leGFtcGxlLmNvbS9 pc19yb290Ijp0cnVlfQ . dBjftJeZ4CVPmB92K27uhbUJU 1p1r_wW1gFWFOEjXk Header Body (‘Claims’) Cryptographic Signature
  30. JSON Web Tokens (JWT) Base64Url-decode the parts to find the

    juicy bits: { "typ":"JWT", "alg":"HS256" } { "iss”:”http://trustyapp.com/”, "exp": 1300819380, “sub”: ”users/8983462”, “scope”: “self api/buy” } tß´—™à%O˜v+nî…SZu¯µ€U…8H× Header Body (‘Claims’) Cryptographic Signature
  31. JSON Web Tokens (JWT) The claims body is the best

    part! It can tell: { "iss”:”http://trustyapp.com/”, "exp": 1300819380, “sub”: ”users/8983462”, “scope”: “self api/buy” } Who issued the token
  32. JSON Web Tokens (JWT) The claims body is the best

    part! It can tell: { "iss”:”http://trustyapp.com/”, "exp": 1300819380, “sub”: ”users/8983462”, “scope”: “self api/buy” } Who issued the token When it expires
  33. JSON Web Tokens (JWT) The claims body is the best

    part! It can tell: { "iss”:”http://trustyapp.com/”, "exp": 1300819380, “sub”: ”users/8983462”, “scope”: “self api/buy” } Who issued the token When it expires Who it represents
  34. JSON Web Tokens (JWT) The claims body is the best

    part! It can tell: { "iss”:”http://trustyapp.com/”, "exp": 1300819380, “sub”: ”users/8983462”, “scope”: “self api/buy” } Who issued the token When it expires Who it represents What they can do
  35. JSON Web Tokens (JWT) Great! Why is this useful? •

    Implicitly trusted because it is cryptographically signed (verified not tampered). • It is structured, enabling inter-op between services • It can inform your client about basic access control rules (permissions)* • And the big one: statelessness! *servers must always enforce access control policies
  36. JSON Web Tokens (JWT) So, what’s the catch? • Implicit

    trust is a tradeoff – how long should the token be good for? how will you revoke it? (Another talk: refresh tokens) • You still have to secure your cookies! • You have to be mindful of what you store in the JWT if they are not encrypted. No sensitive info!
  37. Authorization • JWT Claims can have whatever you want •

    Use a scope field that contains a list of permissions for that user • Client can inspect the claims and scope and turn on or off features based on permissions* • *Server must always assert permissions
  38. How do you do it on the JVM? JJWT is

    awesome https://github.com/jwtk/jjwt
  39. How do you do it on the JVM? import io.jsonwebtoken.Jwts;

    import io.jsonwebtoken.SignatureAlgorithm; byte[] key = getSignatureKey(); String jwt = Jwts.builder().setIssuer(“http://trustyapp.com/”) .setSubject(“users/1300819380”) .setExpiration(expirationDate) .put(“scope”, “self api/buy”) .signWith(SignatureAlgorithm.HS256,key) .compact(); Create a JWT:
  40. How do you do it on the JVM? Verify a

    JWT: try { Jws<Claims> jwt = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt); //OK, we can trust this JWT } catch (SignatureException e) { //don't trust the JWT! }
  41. In addition to user authentication and data security, Stormpath can

    handle authentication and authorization for your API, SPA or mobile app. • API Authentication • API Key Management • Authorization • Token Based Authentication • OAuth • JWTs • MFA, SAML, OAuth2 • Multi-Tenancy http://docs.stormpath.com/guides/api-key-management/ Implementations in your Library of choice: https://docs.stormpath.com/home/ Use Stormpath for API Authentication & Security