Skip to content

Commit bd1943f

Browse files
authored
Merge pull request #40 from kylin987/main
安装时随机生成64位的密钥
2 parents 34f0f2e + 8f5e481 commit bd1943f

2 files changed

Lines changed: 45 additions & 4 deletions

File tree

src/Install.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
class Install
66
{
77
public const WEBMAN_PLUGIN = true;
8+
private const ACCESS_PLACEHOLDER = '__JWT_ACCESS_SECRET_KEY__';
9+
private const REFRESH_PLACEHOLDER = '__JWT_REFRESH_SECRET_KEY__';
810

911
/**
1012
* @var array
@@ -46,6 +48,45 @@ public static function installByRelation()
4648
}
4749
//symlink(__DIR__ . "/$source", base_path()."/$dest");
4850
copy_dir(__DIR__ . "/$source", base_path()."/$dest");
51+
self::initJwtSecrets(base_path()."/$dest/app.php");
52+
}
53+
}
54+
55+
/**
56+
* 安装时初始化JWT密钥(64位随机字符串)
57+
* @param string $configFile
58+
* @return void
59+
*/
60+
protected static function initJwtSecrets(string $configFile): void
61+
{
62+
if (!is_file($configFile) || !is_readable($configFile) || !is_writable($configFile)) {
63+
return;
64+
}
65+
66+
$content = file_get_contents($configFile);
67+
if (!is_string($content) || $content === '') {
68+
return;
69+
}
70+
71+
if (strpos($content, self::ACCESS_PLACEHOLDER) === false && strpos($content, self::REFRESH_PLACEHOLDER) === false) {
72+
return;
73+
}
74+
75+
try {
76+
$accessKey = bin2hex(random_bytes(32));
77+
$refreshKey = bin2hex(random_bytes(32));
78+
} catch (\Exception $e) {
79+
return;
80+
}
81+
82+
$updated = str_replace(
83+
[self::ACCESS_PLACEHOLDER, self::REFRESH_PLACEHOLDER],
84+
[$accessKey, $refreshKey],
85+
$content
86+
);
87+
88+
if ($updated !== $content) {
89+
file_put_contents($configFile, $updated);
4990
}
5091
}
5192

src/config/plugin/tinywan/jwt/app.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
/** 算法类型 HS256、HS384、HS512、RS256、RS384、RS512、ES256、ES384、ES512、PS256、PS384、PS512 */
77
'algorithms' => 'HS256',
88

9-
/** access令牌秘钥 */
10-
'access_secret_key' => '5e923d88405f79ad02e9161183853e57ece80c65315ff684c5e7efde25881f28',
9+
/** access令牌秘钥(安装时自动生成64位随机值) */
10+
'access_secret_key' => '__JWT_ACCESS_SECRET_KEY__',
1111

1212
/** access令牌过期时间,单位:秒。默认 2 小时 */
1313
'access_exp' => 7200,
1414

15-
/** refresh令牌秘钥 */
16-
'refresh_secret_key' => '0c7fc8d5e58be9a5d59527be32740ba5c3c85dc534e8d90a402a529cac94366a',
15+
/** refresh令牌秘钥(安装时自动生成64位随机值) */
16+
'refresh_secret_key' => '__JWT_REFRESH_SECRET_KEY__',
1717

1818
/** refresh令牌过期时间,单位:秒。默认 7 天 */
1919
'refresh_exp' => 604800,

0 commit comments

Comments
 (0)