SoFunction
Updated on 2025-04-11

Implement anti-theft chain function based on SpringBoot

1. Anti-theft chain concept

Anti-theft chaining is a technique that restricts resources to access sources, usually by checking the HTTP request headerRefererfields to implement. If the request's source is not the allowed domain name, the request is rejected. In addition, you can also combineTokenand timestamps further improve security, ensuring that the link can only be valid for a certain period of time.

2. Anti-theft chain principle

  • Referer Verification
    • HTTP Referer is a field attached to the browser when sending a request, which indicates the source page of the request.
    • The server can deny access requests from other sources by checking whether Referer is a trusted domain name.
  • Token Verification
    • The server generates a signed access link (including a token) for a legal request, and the client carries the token when accessing.
    • The server judges the legality of the request by verifying whether the token is correct.
  • Time limit
    • Limit the validity period of the link by attaching a timestamp parameter in the request.
    • The server verifies the difference between the timestamp of the request and the current time, and requests outside the range will be rejected.

Through the above three mechanisms, the security of resource anti-theft chain can be significantly improved.

III. Project structure

Here is the directory structure of the sample project:

src
├── main
│   ├── java
│   │   └── 
│   │       ├── 
│   │       ├── filter
│   │       │   ├── 
│   │       │   ├── 
│   │       │   └── 
│   └── resources
│       └── static
│           └── images
                     └──

4. Core code implementation

1. Main application portal

package ;

import ;
import ;
import ;
import ;
import ;

@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      (, args);
   }
   @Bean
   public FilterRegistrationBean<StaticResourceFilter> staticResourceFilter() {
      FilterRegistrationBean<StaticResourceFilter> registrationBean = new FilterRegistrationBean<>();
      (new StaticResourceFilter());
      ("/images/*");
      return registrationBean;
   }
}

2. Static resource access filter

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class StaticResourceFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // validate Referer
        String referer = ("Referer");
        String allowedDomain = "http://localhost:8088";
        if (referer == null || !(allowedDomain)) {
            ().write("403 Forbidden: Hotlinking not allowed");
            return;
        }

        // validate Token
        if (!(httpRequest, httpResponse)) {
            return;
        }

        // validate Timestamp
        if (!(httpRequest, httpResponse)) {
            return;
        }

        (request, response);
    }
}

3. Token verification tool

package ;

import ;
import ;
import ;

public class TokenValidator {

    public static boolean validateToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = ("token");
        String validToken = "your-predefined-token"; //set your predefined token here

        if (token == null || !(validToken)) {
            ().write("403 Forbidden: Invalid Token");
            return false;
        }

        return true;
    }
}

4. Time limit verification tool

package ;

import ;
import ;
import ;
import ;

public class TimeValidator {

    private static final long ALLOWED_TIME_DIFF = 300; // offset in seconds( 300 seconds)

    public static boolean validateTimestamp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String timestampStr = ("timestamp");

        if (timestampStr == null) {
            ().write("403 Forbidden: Missing Timestamp");
            return false;
        }

        try {
            long timestamp = (timestampStr);
            long currentTimestamp = ().getEpochSecond();

            if ((currentTimestamp - timestamp) > ALLOWED_TIME_DIFF) {
                ().write("403 Forbidden: Timestamp Expired");
                return false;
            }
        } catch (NumberFormatException e) {
            ().write("403 Forbidden: Invalid Timestamp");
            return false;
        }

        return true;
    }
}

5. Static resource example

Put a picture file 711815.jpegPut insrc/main/resources/static/imagesIn the folder.

The above are just some key codes.

5. Test method

  • Start the Spring Boot project.

  • Test access to image resources:

curl -X GET "http://localhost:8088/static/?token=your-predefined-token&timestamp=$(date +%s)" -H "Referer: http://localhost:8088"
  • Check the following situations:

    • If Referer is incorrect, return403 Forbidden: Hotlinking not allowed
    • If the Token is invalid, return403 Forbidden: Invalid Token
    • If the timestamp timed out, return403 Forbidden: Timestamp Expired

Through this article, you can learn how to protect theft chain of resources through Referer verification, Token verification, and time limits. If you have other questions or needs, please feel free to discuss further!

This is the end of this article about implementing anti-theft link function based on SpringBoot. For more related SpringBoot anti-theft link content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!