CS5220 Advanced Topics in Web Programming Secure REST API Chengyu Sun California State University, Los Angeles
Web Application Security Client Server request who are you? Authentication username/password (Access Control) Authorization you’re not authorized to access Connection Security
HTTP Secure (HTTPS) HTTP over SSL/TLS Configure SSL in Tomcat - http://tomcat.apache.org/tomcat-8.5-doc/ssl-howto.html
Basic Security Implementation Database Server Client /login ?? users /api/user/1 ?? ?? How to store passwords properly?? What happens if authentication is successful?? How does the server authenticate/authorize subsequent requests??
Storing Passwords … Hash stored passwords Why?? How?? Encryption vs Hashing?? How to check against hashed passwords?? Common attack on hashed passwords Brute force and some variations Dictionary
… Storing Passwords Common defenses Long and random passwords Make cryptographic hash functions slower Salt
Cryptographic Hash Function… String of arbitrary length n bits digest Properties Given a hash value, it’s virtually impossible to find a message that hashes to this value Given a message, it’s virtually impossible to find another message that hashes to the same value It’s virtually impossible to find two messages that hash to the same value A.K.A. One-way hashing, message digest, digital fingerprint
…Cryptographic Hash Function Common usage Store passwords, software checksum … Popular algorithms Good for password hashing: Argon2, PBKDF2, scrypt, bcrypt Not good for password hashing: MD5 (broken), SHA and variants
bcrypt hash Example abcd $2a$10$aol3r6 … kH/mkyO zB06fcQQOQa … U5.r3rSZI6 128 bit salt encoded in 22 characters 184 bit hash encoded in 31 characters Cost parameter Algorithm version
bcrypt Libraries BcryptPasswordEncoder in org.springframework.security:spring-security-crypto jBcrypt – org.mindrot:jbcrypt
Session-Based Security Database Server Client /login ?? users /api/user/1 ?? What happens if authentication is successful?? What does the server authenticate/authorize subsequent requests?? Why is it not suitable for RESTful web service??
Security without Session What’s wrong with sending username and password in every request? How about using a access key / token instead? Issues need to be considered: access control, performance, expiration, revocation
JSON Web Token (JWT) JWT = JSON object + Signature Example The JSON object contains the identity and authorization of a user, a.k.a. claims The actual content of JSON is up to the application The signature is the hash of the JSON object and a secret key (that only the server knows) Example JSON: { “username”: “john”, “role”: “admin” } Signature: HS256( JSON, “some secrete” )
How JWT Works … Login on the server Receives username and password Loads user information from database Creates a JWT Sends the JWT to client
… How JWT Works In subsequent requests Client includes JWT in each request Header E.g. Authorization: Bearer <token> Request parameter Cookie Server verifies the signature in JWT (How??) If signature is valid, server grants access based on JWT (no need to access database again)
More About JWT https://jwt.io/ Header, payload, and signature Predefined claims in payload sub: subject exp: expiration time iat: Issued at JWT does not provide a way to revoke tokens
Implementation Strategy … Create and verify token using Java JWT Extract token from request header, parameter, or cookie (easily done with Spring controller methods) HttpServletRequest @RequestHeader @RequestParam @CookieValue
… Implementation Strategy Use Servlet Filter, or Spring Handler Interceptor, or @ControllerAdvice Verify token, and create a User object from the token if the signature is valid Pass the User object to controller methods as a request attribute or @ModelAttribute
Servlet Filter Intercept, examine, and/or modify request and response Servlet/JSP
Servlet Filter Example web.xml <filter> and <filter-mapping> Modify request Modify response
Spring Handler Interceptor Serve the same purpose as servlet filter Configured as Spring beans, i.e. support dependency injection Handler Interceptor request response Controller
Implement a Handler Interceptor Implement HandlerInterceptor or inherits from HandlerInterceptorAdapter preHandle() – called before the controller method is invoked postHandle() – called after the controller method is invoked (but before view is generated) afterCompletion() – called after the request processing is completed (i.e. after view is generated)
URL Mapping for Handler Interceptor <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/api/**" /> <bean class=“some.Interceptor"></bean> </mvc:interceptor> </mvc:interceptors>
Use Model Methods in @ControllerAdvice Model Methods can create @ModelAttribute that are used by subsequent controller methods @ControllerAdvice public class SomeAdvice { @ModelAttribute(“currentUser”) public User getUserFromJwt( … ) { … } @ModelAttribute public void addMultipleAttributes( ModelMap models ) {…} }