Basic Spring Security tips before going into production
Introduction
In general, web APIs are exposed to the Internet, so they need security mechanisms to prevent abuse, protect sensitive data, and ensure that only authenticated and authorized users can access them. Thus, web API security is crucial.
Below are some of the basic points that would help you to start the basic security checks —
1. Url protection
- Allow access to everyone to a given URL
- Secure URL based on roles.
- Secure URL based on multiple roles.
.antMatchers(“/register”,”/login”,”/user”,”/admin”)
access(“hasRole(‘ADMIN’) and hasIpAddress(‘123.123.123.123’)”)
Use the access method to use SPEL for more complicated security.
2. CSRF Token
A CSRF attack occurs when a website uses cookies for any reason and a malicious script is executed on the client/user side to perform any task such as fund transfer or password change without the user’s knowledge.
REST applications are immune to CSRF attacks if they do not use cookies. So, no cookies = no CSRF.
Usually, most of the people disable(in demo code) because they won’t be able to call /logout
URL with the GET
method as it requires you to submit it via POST
with _csrf
token. Check more details about CSRF here
3. Session Fixation Attack
This is the type of attack where one can steal your current session by offering their URL of the same website and append JSESSIONID
it into the URL, with the URL rewrite approach. Spring Security Framework has taken care of this by default and it migrates the session once the user logs in. The corresponding configuration would be -
http.sessionManagement()
.sessionFixation().migrateSession()
You should use above only when you are using session based application. For REST based application this might not be needed.
4. Securing session cookie:
The malicious script can read your cookie information from the browser end so you need to make sure that your cookie is secured and accessible by server-side code by making them HttpOnly
. For that, you can add the below config in your application.properties
-
server.servlet.session.cookie.http-only=true
5. Running your app on Https:
Make sure that you use HTTPS in production and in that case you can force your cookies to travel over HTTPS protocol only by adding the below config in your application.properties
.
server.servlet.session.cookie.secure=true
and to force HTTPS connection add below lines in configure() method (this won’t be enough though because you have to get your public/private key setup also using the key tool)
http.requiresChannel().requiresSecure();
6. Applying CSP:
User Content security policy to avoid any XSS attacks. Spring security by default provides various security headers. But it does not add Content security policy headers you can add them in your security config file like below.
7. Password hashing:
Password hashing is a one-way function that is impossible to decrypt. Keeping the password in open plain text is open for anyone to read. This can pose a great security threat as anyone in your organization or outside who can gain the access to DB can read the password. It is a must-have thing that everyone should follow.
Spring security provides various algorithms to support password hashing.
bcrypt
password encoder by default.
PasswordEncoderFactories.createDelegatingPasswordEncoder()
Or use other also supported
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
Check here for more sets of algorithms supported by this factory class.
8. Enabling method level security
Spring Security supports “Method Level Security” by using AOP. @PreAuthorized
can be used to secure methods at the controller layer. This is similar to URL protection but the difference is that @PreAuthorized
triggers when your controller code is about to execute. Also, you can use the SPEL expression to allow or deny requests based on security attributes such as, if the request is read_only
and then update or delete operations should be rejected.
Also, it can help you to organize the security-related definitions within the code adjacent to the controller definitions.
9. Securing your application.properties
Security should be applied not only from outside but should also be protected from inside as well. Like encryption and decryption of database passwords or any other config passwords. Please check my other post on how you can secure the application.properties
in spring boot.
10. Prevent DDOS attack
This should be addressed by adjusting several security parameters such as session timeouts, security header checks, memory leak handling, and POST request timeouts to ensure that no one posts a large request payload, among others. To counteract such security threats, you’ll need to put in some effort. There are cloud providers which prevent such type attacks such as AWS Shield or Google Cloud armor
11. What else we can do ??
Security isn’t restricted to the topics we’ve discussed thus far. These considerations may not be sufficient when working with mission-critical systems, such as those in the finance industry, where security is paramount. However, these ideas might serve as a good starting point for addressing some of the more fundamental and sophisticated issues.
Occasionally, addressing a CVE (Common Vulnerability and Exposure) error may pose a security risk. You may need to upgrade the underlining library in this situation, as the library has security vulnerabilities that you may or may not be aware of. Do you remember the log4j security crisis? 😊
Thank you for your time. Follow me for more such updates.😊