修复认证与基础安全链路
This commit is contained in:
@@ -11,15 +11,22 @@ namespace App\Providers;
|
||||
|
||||
use App\Listeners\SaveMarriageSystemMessage;
|
||||
use App\Models\Sysparam;
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* 类功能:注册应用级服务与全局安全配置。
|
||||
*/
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register any application services.
|
||||
* 注册应用级服务容器绑定。
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
@@ -27,10 +34,13 @@ class AppServiceProvider extends ServiceProvider
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
* 引导应用启动阶段的全局配置与事件订阅。
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
// 注册登录入口限流器,阻断爆破和批量注册滥用。
|
||||
$this->registerAuthRateLimiters();
|
||||
|
||||
// 注册婚姻系统消息订阅者(结婚/婚礼/离婚通知写入聊天历史)
|
||||
Event::subscribe(SaveMarriageSystemMessage::class);
|
||||
|
||||
@@ -62,4 +72,49 @@ class AppServiceProvider extends ServiceProvider
|
||||
// 在安装初期表不存在时忽略,防止应用崩溃
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册聊天室前台登录与隐藏后台登录的独立限流器。
|
||||
*/
|
||||
private function registerAuthRateLimiters(): void
|
||||
{
|
||||
RateLimiter::for('chat-login', function (Request $request): Limit {
|
||||
return Limit::perMinute(5)
|
||||
->by($this->buildAuthRateLimitKey($request, 'chat-login'))
|
||||
->response(function (Request $request, array $headers) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => '登录尝试过于频繁,请 1 分钟后再试。',
|
||||
], 429, $headers);
|
||||
});
|
||||
});
|
||||
|
||||
RateLimiter::for('admin-hidden-login', function (Request $request): Limit {
|
||||
return Limit::perMinute(5)
|
||||
->by($this->buildAuthRateLimitKey($request, 'admin-hidden-login'))
|
||||
->response(function (Request $request, array $headers) {
|
||||
$response = redirect()->route('admin.login')
|
||||
->withInput($request->except(['password', 'captcha']))
|
||||
->withErrors(['username' => '登录尝试过于频繁,请 1 分钟后再试。']);
|
||||
|
||||
foreach ($headers as $headerName => $headerValue) {
|
||||
$response->headers->set($headerName, $headerValue);
|
||||
}
|
||||
|
||||
$response->setStatusCode(429);
|
||||
|
||||
return $response;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造登录限流键,按场景 + 用户名 + IP 维度隔离计数。
|
||||
*/
|
||||
private function buildAuthRateLimitKey(Request $request, string $scene): string
|
||||
{
|
||||
$username = Str::lower(trim((string) $request->input('username', 'guest')));
|
||||
|
||||
return implode('|', [$scene, $username, $request->ip()]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user