最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot實(shí)現(xiàn)License認(rèn)證(只校驗(yàn)有效期)的詳細(xì)過程

 更新時間:2024年04月16日 10:33:34   作者:冬天vs不冷  
License也就是版權(quán)許可證書,一般用于收費(fèi)軟件給付費(fèi)用戶提供的訪問許可證明,這篇文章主要介紹了SpringBoot實(shí)現(xiàn)License認(rèn)證(只校驗(yàn)有效期),需要的朋友可以參考下

一、License介紹

License也就是版權(quán)許可證書,一般用于收費(fèi)軟件給付費(fèi)用戶提供的訪問許可證明

應(yīng)用場景

  • 應(yīng)用部署在客戶的內(nèi)網(wǎng)環(huán)境
  • 這種情況開發(fā)者無法控制客戶的網(wǎng)絡(luò)環(huán)境,也不能保證應(yīng)用所在服務(wù)器可以訪問外網(wǎng)
  • 因此通常的做法是使用服務(wù)器許可文件,在應(yīng)用啟動的時候加載證書
  • 然后在登錄或者其他關(guān)鍵操作的地方校驗(yàn)證書的有效性

License授權(quán)原理

使用開源的證書管理引擎TrueLicense

  • 生成密鑰對,使用Keytool生成公私鑰證書庫
  • 授權(quán)者保留私鑰,使用私鑰和使用日期生成證書license
  • 公鑰與生成的證書給使用者(放在驗(yàn)證的代碼中使用),驗(yàn)證證書license是否在有效期內(nèi)

二、授權(quán)者生成密鑰對

  • 需要關(guān)注以及修改的參數(shù):storepass(私鑰庫的密碼)、keypass(私鑰的密碼)
  • 其他參數(shù)使用默認(rèn)值即可,validity(私鑰的有效期)設(shè)置十年就可以,因?yàn)橐院髸ㄟ^私鑰和證書有效期生成證書license
## 1. 生成私匙庫
# validity:私鑰的有效期(單位:天)
# alias:私鑰別稱
# keystore: 私鑰庫文件名稱(生成在當(dāng)前目錄)
# storepass:私鑰庫的密碼(獲取keystore信息所需的密碼) 
# keypass:私鑰的密碼
# dname 證書個人信息
# 	CN 為你的姓名
#	OU 為你的組織單位名稱
#	O 為你的組織名稱
#	L 為你所在的城市名稱
#	ST 為你所在的省份名稱
#	C 為你的國家名稱 或 區(qū)號
keytool -genkeypair -keysize 1024 -validity 3650 -alias "privateKey" -keystore "privateKeys.keystore" -storepass "public_password1234" -keypass "private_password1234" -dname "CN=localhost, OU=localhost, O=localhost, L=SH, ST=SH, C=CN"
## 2. 把私匙庫內(nèi)的公匙導(dǎo)出到一個文件當(dāng)中
# alias:私鑰別稱
# keystore:私鑰庫的名稱(在當(dāng)前目錄查找)
# storepass: 私鑰庫的密碼
# file:證書名稱
keytool -exportcert -alias "privateKey" -keystore "privateKeys.keystore" -storepass "public_password1234" -file "certfile.cer"
## 3. 再把這個證書文件導(dǎo)入到公匙庫
# alias:公鑰別稱
# file:證書名稱
# keystore:公鑰文件名稱(生成在當(dāng)前目錄)
# storepass:私鑰庫的密碼
keytool -import -alias "publicCert" -file "certfile.cer" -keystore "publicCerts.keystore" -storepass "public_password1234"

上述命令執(zhí)行完成后會在當(dāng)前目錄生成三個文件:

  • certfile.cer 認(rèn)證證書文件,已經(jīng)沒用了,可以刪除
  • privateKeys.keystore 私鑰文件,自己保存,以后用于生成license.lic證書
  • publicKeys.keystore 公鑰文件,以后會和license.lic證書一起放到使用者項目里

三、授權(quán)者生成license.lic證書

pom.xml

<!-- License -->
<dependency>
    <groupId>de.schlichtherle.truelicense</groupId>
    <artifactId>truelicense-core</artifactId>
    <version>1.33</version>
</dependency>

1、License生成類

import de.schlichtherle.license.*;
import lombok.extern.slf4j.Slf4j;
import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.prefs.Preferences;
@Slf4j
public class LicenseCreator {
    private final static X500Principal DEFAULT_HOLDER_AND_ISSUER = 
    	new X500Principal("CN=localhost, OU=localhost, O=localhost, L=SH, ST=SH, C=CN");
    /**
     * @description main方法生成license文件
     * @author xuchang
     * @date 2024/3/4 15:51:14
     */
    public static void main(String[] args) throws IOException {
        LicenseCreatorParam param = new LicenseCreatorParam();
        // 證書主題
        param.setSubject("license");
        // 密鑰別稱
        param.setPrivateAlias("privateKey");
        // 私鑰密碼
        param.setKeyPass("private_password1234");
        // 私鑰庫的密碼
        param.setStorePass("public_password1234");
        // 證書生成路徑
        param.setLicensePath("/Users/xuchang/Documents/license/license.lic");
        // 私鑰存儲路徑
        param.setPrivateKeysStorePath("/Users/xuchang/Documents/license/privateKeys.keystore");
        // 證書生成時間-當(dāng)前時間
        param.setIssuedTime(new Date());
        LocalDateTime localDateTime = LocalDateTime.of(2024, 12, 31, 23, 59, 59);
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        // 證書過期時間-2024年12月31日23:59:59
        param.setExpiryTime(date);
        // 用戶類型
        param.setConsumerType("user");
        // 用戶數(shù)量
        param.setConsumerAmount(1);
        // 證書描述
        param.setDescription("證書描述信息");
        // 生成證書
        LicenseCreator licenseCreator = new LicenseCreator();
        licenseCreator.generateLicense(param);
    }
    // 生成License證書
    public void generateLicense(LicenseCreatorParam param) {
        try {
            LicenseManager licenseManager = new LicenseManager(initLicenseParam(param));
            LicenseContent licenseContent = initLicenseContent(param);
            licenseManager.store(licenseContent, new File(param.getLicensePath()));
        } catch (Exception e) {
            log.error("證書生成失敗", e);
        }
    }
    // 初始化證書生成參數(shù)
    private static LicenseParam initLicenseParam(LicenseCreatorParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
        // 設(shè)置對證書內(nèi)容加密的秘鑰
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        // 自定義KeyStoreParam
        KeyStoreParam privateStoreParam = new CustomKeyStoreParam(LicenseCreator.class
                , param.getPrivateKeysStorePath()
                , param.getPrivateAlias()
                , param.getStorePass()
                , param.getKeyPass());
        // 組織License參數(shù)
        return new DefaultLicenseParam(param.getSubject()
                , preferences
                , privateStoreParam
                , cipherParam);
    }
    // 設(shè)置證書生成正文信息
    private static LicenseContent initLicenseContent(LicenseCreatorParam param) {
        LicenseContent licenseContent = new LicenseContent();
        licenseContent.setHolder(DEFAULT_HOLDER_AND_ISSUER);
        licenseContent.setIssuer(DEFAULT_HOLDER_AND_ISSUER);
        licenseContent.setSubject(param.getSubject());
        licenseContent.setIssued(param.getIssuedTime());
        licenseContent.setNotBefore(param.getIssuedTime());
        licenseContent.setNotAfter(param.getExpiryTime());
        licenseContent.setConsumerType(param.getConsumerType());
        licenseContent.setConsumerAmount(param.getConsumerAmount());
        licenseContent.setInfo(param.getDescription());
        return licenseContent;
    }
}

License生成類需要的參數(shù)類

@Data
public class LicenseCreatorParam {
    /**
     * 證書subject
     */
    private String subject;
    /**
     * 密鑰別稱
     */
    private String privateAlias;
    /**
     * 公鑰密碼(需要妥善保管,不能讓使用者知道)
     */
    private String keyPass;
    /**
     * 私鑰庫的密碼
     */
    private String storePass;
    /**
     * 證書生成路徑
     */
    private String licensePath;
    /**
     * 私鑰存儲路徑
     */
    private String privateKeysStorePath;
    /**
     * 證書生效時間
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date issuedTime;
    /**
     * 證書失效時間
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date expiryTime;
    /**
     * 用戶類型
     */
    private String consumerType;
    /**
     * 用戶數(shù)量
     */
    private Integer consumerAmount;
    /**
     * 描述信息
     */
    private String description;
}

自定義KeyStoreParam

public class CustomKeyStoreParam extends AbstractKeyStoreParam {
    private final String storePath;
    private final String alias;
    private final String storePwd;
    private final String keyPwd;
    public CustomKeyStoreParam(Class clazz, String resource, String alias, String storePwd, String keyPwd) {
        super(clazz, resource);
        this.storePath = resource;
        this.alias = alias;
        this.storePwd = storePwd;
        this.keyPwd = keyPwd;
    }
    @Override
    public String getAlias() {
        return alias;
    }
    @Override
    public String getStorePwd() {
        return storePwd;
    }
    @Override
    public String getKeyPwd() {
        return keyPwd;
    }
    @Override
    public InputStream getStream() throws IOException {
        return Files.newInputStream(Paths.get(storePath));
    }
}

2、main方法生成license.lic注意事項

以上都是授權(quán)者需要做的,下面說下使用者需要的配置

四、使用者配置

pom.xml

<!-- License -->
<dependency>
    <groupId>de.schlichtherle.truelicense</groupId>
    <artifactId>truelicense-core</artifactId>
    <version>1.33</version>
</dependency>

1、License校驗(yàn)類

@Slf4j
public class LicenseVerify {
    // 安裝License證書
    public synchronized LicenseContent install(LicenseVerifyParam param) {
        LicenseContent result = null;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 1. 安裝證書
        try {
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
            licenseManager.uninstall();
            result = licenseManager.install(new File(param.getLicensePath()));
            log.info(MessageFormat.format("證書安裝成功,證書有效期:{0} - {1}", 
            	format.format(result.getNotBefore()), format.format(result.getNotAfter())));
        } catch (Exception e) {
            log.error("證書安裝失敗: {}", e.getMessage());
        }
        return result;
    }
    // 校驗(yàn)License證書
    public boolean verify() {
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 2. 校驗(yàn)證書
        try {
            LicenseContent licenseContent = licenseManager.verify();
            log.info(MessageFormat.format("證書校驗(yàn)通過,證書有效期:{0} - {1}", 
            	format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter())));
            return true;
        } catch (Exception e) {
            log.error("證書校驗(yàn)失敗: {}", e.getMessage());
            return false;
        }
    }
    // 初始化證書生成參數(shù)
    private LicenseParam initLicenseParam(LicenseVerifyParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class
                , param.getPublicKeysStorePath()
                , param.getPublicAlias()
                , param.getStorePass()
                , null);
        return new DefaultLicenseParam(param.getSubject()
                , preferences
                , publicStoreParam
                , cipherParam);
    }
}

License校驗(yàn)類需要的參數(shù)

@Data
public class LicenseVerifyParam {
    /**
     * 證書subject
     */
    private String subject;
    /**
     * 公鑰別稱
     */
    private String publicAlias;
    /**
     * 訪問公鑰庫的密碼
     */
    private String storePass;
    /**
     * 證書生成路徑
     */
    private String licensePath;
    /**
     * 密鑰庫存儲路徑
     */
    private String publicKeysStorePath;
}

自定義KeyStoreParam(與授權(quán)者一樣)

public class CustomKeyStoreParam extends AbstractKeyStoreParam {
    private final String storePath;
    private final String alias;
    private final String storePwd;
    private final String keyPwd;
    public CustomKeyStoreParam(Class clazz, String resource,String alias,String storePwd,String keyPwd) {
        super(clazz, resource);
        this.storePath = resource;
        this.alias = alias;
        this.storePwd = storePwd;
        this.keyPwd = keyPwd;
    }
    @Override
    public String getAlias() {
        return alias;
    }
    @Override
    public String getStorePwd() {
        return storePwd;
    }
    @Override
    public String getKeyPwd() {
        return keyPwd;
    }
    @Override
    public InputStream getStream() throws IOException {
        return Files.newInputStream(Paths.get(storePath));
    }
}

LicenseManager的單例

public class LicenseManagerHolder {
    private static volatile LicenseManager LICENSE_MANAGER;
    public static LicenseManager getInstance(LicenseParam param){
        if(LICENSE_MANAGER == null){
            synchronized (LicenseManagerHolder.class){
                if(LICENSE_MANAGER == null){
                    LICENSE_MANAGER = new LicenseManager(param);
                }
            }
        }
        return LICENSE_MANAGER;
    }
}

2、項目啟動時安裝證書

application.poperties配置

#License配置
# 與創(chuàng)建license.lic設(shè)置的值一樣
license.subject=license
# 與生成密鑰對的公鑰別稱一樣
license.publicAlias=publicCert
# 私鑰庫的密碼
license.storePass=public_password1234

license.lic證書和publicCerts.keystore放入resources資源目錄下

springboot項目啟動后執(zhí)行操作

@Slf4j
@Component
public class LicenseCheckRunner implements ApplicationRunner {
    /**
     * 證書subject
     */
    @Value("${license.subject}")
    private String subject;
    /**
     * 公鑰別稱
     */
    @Value("${license.publicAlias}")
    private String publicAlias;
    /**
     * 訪問公鑰庫的密碼
     */
    @Value("${license.storePass}")
    private String storePass;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("++++++++ 開始安裝證書 ++++++++");
        LicenseVerifyParam param = new LicenseVerifyParam();
        param.setSubject(subject);
        param.setPublicAlias(publicAlias);
        param.setStorePass(storePass);
        // 相對路徑resources資源目錄
        String resourcePath = getClass().getClassLoader().getResource("").getPath();
        // 證書地址
        param.setLicensePath(resourcePath + "license.lic");
        // 公鑰地址
        param.setPublicKeysStorePath(resourcePath + "publicCerts.keystore");
        // 安裝證書
        LicenseVerify licenseVerify = new LicenseVerify();
        licenseVerify.install(param);
        log.info("++++++++ 證書安裝結(jié)束 ++++++++");
    }
}
  • 如果想要當(dāng)前配置作為公共類,對于多個微服務(wù),只想要一個服務(wù)resources/license下配置證書和公鑰
  • 獲取公共服務(wù)里證書和公鑰的輸入流,然后拷貝到當(dāng)前服務(wù)下

啟動安裝成功

啟動安裝失?。ㄗC書過期)

3、設(shè)置攔截器

配置攔截器

@Slf4j
public class LicenseCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LicenseVerify licenseVerify = new LicenseVerify();
        // 校驗(yàn)證書是否有效
        boolean verifyResult = licenseVerify.verify();
        if (verifyResult) {
            return true;
        } else {
            response.setCharacterEncoding("utf-8");
            Map<String, String> result = new HashMap<>(1);
            result.put("result", "您的證書無效,請核查服務(wù)器是否取得授權(quán)或重新申請證書!");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
    }
}

注冊攔截器

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LicenseCheckInterceptor());
    }
}

證書有效期內(nèi)請求接口

證書過期請求接口

到此這篇關(guān)于SpringBoot實(shí)現(xiàn)License認(rèn)證(只校驗(yàn)有效期)的文章就介紹到這了,更多相關(guān)SpringBoot License認(rèn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 使用SpringBoot中的Schedule定時發(fā)送郵件的方法

    使用SpringBoot中的Schedule定時發(fā)送郵件的方法

    在SpringBoot中,你可以使用@Scheduled注解來創(chuàng)建定時任務(wù),@Scheduled注解可以應(yīng)用于方法上,表示這個方法是一個定時任務(wù),可以根據(jù)指定的時間間隔或固定時間執(zhí)行,本文就給大家介紹一下如何使用SpringBoot中的Schedule定時發(fā)送郵件,需要的朋友可以參考下
    2023-08-08
  • Spring框架中@Lazy延遲加載原理和使用詳解

    Spring框架中@Lazy延遲加載原理和使用詳解

    這篇文章主要介紹了Spring框架中@Lazy延遲加載原理和使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-05-05
  • java實(shí)現(xiàn)分頁顯示效果

    java實(shí)現(xiàn)分頁顯示效果

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)頁顯示效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • 聊一聊Java中的Steam流

    聊一聊Java中的Steam流

    當(dāng)我們需要處理的數(shù)據(jù)量很大的時候,為了提高性能,就需要使用到并行處理,這樣的處理方式是很復(fù)雜的,流可以幫助開發(fā)者節(jié)約寶貴的時間,讓以上的事情變得輕松,本文就和大家聊一聊Java中的Steam流,感興趣的同學(xué)跟著小編一起來看看吧
    2023-07-07
  • springboot整合ehcache和redis實(shí)現(xiàn)多級緩存實(shí)戰(zhàn)案例

    springboot整合ehcache和redis實(shí)現(xiàn)多級緩存實(shí)戰(zhàn)案例

    這篇文章主要介紹了springboot整合ehcache和redis實(shí)現(xiàn)多級緩存實(shí)戰(zhàn)案例,從源碼角度分析下多級緩存實(shí)現(xiàn)原理,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2023-08-08
  • spring @Cacheable擴(kuò)展實(shí)現(xiàn)緩存自動過期時間及自動刷新功能

    spring @Cacheable擴(kuò)展實(shí)現(xiàn)緩存自動過期時間及自動刷新功能

    用過spring cache的朋友應(yīng)該會知道,Spring Cache默認(rèn)是不支持在@Cacheable上添加過期時間的,雖然可以通過配置緩存容器時統(tǒng)一指定,本文主要介紹了如何基于spring @Cacheable擴(kuò)展實(shí)現(xiàn)緩存自動過期時間以及緩存即將到期自動刷新,
    2024-02-02
  • Spring中注解方式的異步請求

    Spring中注解方式的異步請求

    今天給大家整理了Spring中注解方式的異步請求的知識點(diǎn),對正在學(xué)習(xí)java的小伙伴們很有幫助,需要的朋友可以參考下
    2021-06-06
  • Spring?IOC?常用注解與使用實(shí)例詳解

    Spring?IOC?常用注解與使用實(shí)例詳解

    這篇文章主要介紹了Spring?IOC?常用注解與使用,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • Java數(shù)據(jù)結(jié)構(gòu)之紅黑樹的真正理解

    Java數(shù)據(jù)結(jié)構(gòu)之紅黑樹的真正理解

    這篇文章主要為大家詳細(xì)介紹了Java數(shù)據(jù)結(jié)構(gòu)之紅黑樹的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • 23種設(shè)計模式(9) java橋接模式

    23種設(shè)計模式(9) java橋接模式

    這篇文章主要為大家詳細(xì)介紹了java設(shè)計模式之橋接模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11

最新評論

建始县| 通河县| 屏山县| 鲜城| 崇文区| 敖汉旗| 和田市| 紫云| 师宗县| 乐平市| 永济市| 叙永县| 林口县| 丘北县| 壶关县| 民权县| 信宜市| 乐东| 五大连池市| 宾阳县| 清水河县| 华宁县| 嵊州市| 甘孜| 永修县| 阿瓦提县| 广安市| 闻喜县| 沂水县| 伊吾县| 会昌县| 郧西县| 宜昌市| 佛坪县| 班戈县| 景宁| 河间市| 新民市| 赞皇县| 贵德县| 娄烦县|