Use TrueLicense to generate and verify License in Spring Boot project

TrueLicense is a Java software license management library that can be used to generate, verify and manage software licenses. Using TrueLicense in Spring Boot projects can help developers easily implement software license management. The following describes how to use TrueLicense in Spring Boot.

  1. Introduce TrueLicense dependency

Add the following dependencies to pom.xml:

<dependency>
    <groupId>net.truelicense</groupId>
    <artifactId>truelicense-core</artifactId>
    <version>3.4.0</version>
</dependency>
  1. Create a License Generator

Creating a License generator in Spring Boot requires implementing the LicenseManagerBuilder interface of TrueLicense. You can use the DefaultLicenseManagerBuilder provided by TrueLicense or customize the implementation.

import net.truelicense.api.LicenseManager;
import net.truelicense.api.LicenseManagerBuilder;
import net.truelicense.core.DefaultLicenseManagerBuilder;
import org.springframework.stereotype.Component;

@Component
public class MyLicenseManagerBuilder implements LicenseManagerBuilder {<!-- -->
    @Override
    public LicenseManager build() {<!-- -->
        return new DefaultLicenseManagerBuilder()
                .withSerial("0000-0000-0000-0000") //Set the serial number
                .withStorePass("password") //Set the keystore password
                .withKeyAlias("alias") // Set key alias
                .withKeyPass("password") // Set key password
                .withLicenseProvider(MyLicenseProvider.class) //Set the License provider
                .build();
    }
}

In the above code, the DefaultLicenseManagerBuilder is used to create the LicenseManager object and set the serial number, keystore password, key alias, key password and License provider. Among them, MyLicenseProvider is a custom License provider that needs to be created in the next step.

  1. Create a License provider

To create a License provider in a Spring Boot project, you need to implement the LicenseProvider interface of TrueLicense. The License provider is responsible for generating and validating licenses. Here’s an example:

import net.truelicense.api.License;
import net.truelicense.api.LicenseProvider;
import net.truelicense.core.Base64Encoder;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Component
public class MyLicenseProvider implements LicenseProvider {<!-- -->
    @Override
    public boolean canCreate(Properties properties) {<!-- -->
        return true;
    }

    @Override
    public String generate(Properties properties) throws Exception {<!-- -->
        License license = new License(properties);
        license.setSubject("My Application");
        license.setHolder(new Holder("John Doe"));
        license.setIssued(new Date());
        license.setNotBefore(new Date());
        license.setNotAfter(new Date(System.currentTimeMillis() + 30L * 24L * 60L * 60L * 1000L)); // Validity period is 30 days
        license.setConsumerType(ConsumerType.User);
        license.setConsumerAmount(1);
        license.setInfo("This license is for My Application.");
        return Base64Encoder.encode(license.sign(privateKey()));
    }

    @Override
    public License load() throws Exception {<!-- -->
        URL resource = getClass().getResource("/license.lic");
        try (InputStream inputStream = resource.openStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {<!-- -->
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = reader.readLine()) != null) {<!-- -->
                builder.append(line.trim());
            }
            byte[] bytes = Base64Encoder.decode(builder.toString());
            License license = new License(bytes);
            if (license.verify(publicKey())) {<!-- -->
                return license;
            } else {<!-- -->
                throw new IllegalStateException("Invalid license");
            }
        }
    }

    @Override
    public Map<String, String> getExtra() {<!-- -->
        Map<String, String> extra = new HashMap<>();
        extra.put("Name", "My Application");
        extra.put("Vendor", "My Company");
        return extra;
    }

    @Override
    public Principal getHolder() {<!-- -->
        return new Holder("John Doe");
    }

    @Override
    public String getIssuer() {<!-- -->
        return "My Company";
    }

    private byte[] privateKey() throws Exception {<!-- -->
        URL resource = getClass().getResource("/private.key");
        try (InputStream inputStream = resource.openStream()) {<!-- -->
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            return bytes;
        }
    }

    private byte[] publicKey() throws Exception {<!-- -->
        URL resource = getClass().getResource("/public.key");
        try (InputStream inputStream = resource.openStream()) {<!-- -->
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            return bytes;
        }
    }
}

In the above code, the generate method is used to generate the license, and the load method is used to load the license. Among them, the License object is used to generate the license, and various attributes of the license are set, such as subject, holder, validity period, etc. Loading the license reads the license.lic file from the classpath and then uses the public key to verify the validity of the license.

  1. Verify License

To verify the License in the Spring Boot project, you need to inject the LicenseManager where verification is required, and use the verify method of the LicenseManager to verify the license:

import net.truelicense.api.License;
import net.truelicense.api.LicenseManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyService {<!-- -->
    @Autowired
    private LicenseManager licenseManager;

    public void doSomething() {<!-- -->
        License license = licenseManager.getLicense();
        if (license != null) {<!-- -->
            //Verify license
            if (license.getNotAfter().getTime() < System.currentTimeMillis()) {<!-- -->
                throw new IllegalStateException("License has expired.");
            }
            //Information contained in the license
            String info = license.getInfo();
            // TODO: do something
        } else {<!-- -->
            throw new IllegalStateException("License not found.");
        }
    }
}

In the above code, use @Autowired to inject the LicenseManager, obtain the license in the doSomething method, then verify whether the license has expired, and perform the appropriate operations based on the information contained in the license. If the license is not found, an IllegalStateException is thrown.

The above is how to use TrueLicense to generate and verify licenses in Spring Boot projects. It should be noted that public and private keys are required when generating and verifying licenses. You can use the KeyTool provided by TrueLicense to generate a key pair, or generate a key pair yourself. In addition, the canCreate method needs to be implemented in the License provider to determine whether the license can be generated.