- 生成和验证授权码
- 记录授权时间和过期时间
- 实现授权逻辑
以下是具体的实现方法:
1. 生成和验证授权码
可以使用加密技术生成和验证授权码。授权码中可以包含有效期等信息,并使用密钥进行签名。
示例代码:
java复制代码
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.concurrent.TimeUnit;public class LicenseManager {private static final String SECRET_KEY = "your_secret_key";public static String generateLicense(String userId, long durationInDays) throws Exception {long currentTime = System.currentTimeMillis();long expiryTime = currentTime + TimeUnit.DAYS.toMillis(durationInDays);String data = userId + ":" + expiryTime;Mac sha256HMAC = Mac.getInstance("HmacSHA256");SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), "HmacSHA256");sha256HMAC.init(secretKey);String hash = Base64.getEncoder().encodeToString(sha256HMAC.doFinal(data.getBytes()));return Base64.getEncoder().encodeToString((data + ":" + hash).getBytes());}public static boolean validateLicense(String license) throws Exception {String decodedLicense = new String(Base64.getDecoder().decode(license));String[] parts = decodedLicense.split(":");if (parts.length != 3) return false;String data = parts[0] + ":" + parts[1];String hash = parts[2];Mac sha256HMAC = Mac.getInstance("HmacSHA256");SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), "HmacSHA256");sha256HMAC.init(secretKey);String calculatedHash = Base64.getEncoder().encodeToString(sha256HMAC.doFinal(data.getBytes()));if (!calculatedHash.equals(hash)) return false;long expiryTime = Long.parseLong(parts[1]);return System.currentTimeMillis() <= expiryTime;}
}
2. 记录授权时间和过期时间
通过授权码生成和验证,可以记录和检查授权时间和过期时间。
3. 实现授权逻辑
在Spring Boot应用中,通过拦截器或过滤器来验证每次请求的授权码。
示例代码:
创建一个拦截器
java复制代码
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Component
public class LicenseInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String license = request.getHeader("License-Key");if (license == null || !LicenseManager.validateLicense(license)) {response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "License is invalid or expired");return false;}return true;}
}
注册拦截器
在Spring Boot配置类中注册拦截器:
java复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate LicenseInterceptor licenseInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(licenseInterceptor).addPathPatterns("/**");}
}
4. 使用授权码
公司使用项目时,需要将授权码放在HTTP请求头中:
http复制代码
GET /your/api/endpoint
License-Key: generated_license_key
5. 重新授权
在3个月到期后,需要重新生成并分发新的授权码。可以为此创建一个管理端点来帮助重新授权。
示例代码:
java复制代码
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class LicenseController {@GetMapping("/generateLicense")public String generateLicense(@RequestParam String userId, @RequestParam long durationInDays) throws Exception {return LicenseManager.generateLicense(userId, durationInDays);}
}