$name, 'client_id' => bin2hex(random_bytes(20)), 'client_secret' => bin2hex(random_bytes(20)), 'redirect_uri' => $redirectUri, 'grant_types' => $grantTypes, 'scope' => $scopes, ]); } /** * 验证客户端 */ public static function validateClient(string $clientId, string $clientSecret, string $grantType): bool { $client = OAuthClient::where('client_id', $clientId) ->where('client_secret', $clientSecret) ->first(); if (!$client) { return false; } return in_array($grantType, $client->grant_types); } /** * 创建访问令牌 */ public static function createAccessToken(string $clientId, ?int $userId = null, array $scopes = [], int $expiresIn = 3600): OAuthAccessToken { return OAuthAccessToken::create([ 'client_id' => $clientId, 'user_id' => $userId, 'access_token' => bin2hex(random_bytes(40)), 'expires_at' => now()->addSeconds($expiresIn), 'scope' => $scopes, ]); } /** * 验证访问令牌 * * @param string $token 访问令牌 * @return OAuthAccessToken|null 如果令牌有效返回令牌对象,否则返回null */ public static function validateAccessToken(string $token): ?OAuthAccessToken { $accessToken = OAuthAccessToken::where('access_token', $token) ->where('revoked', false) ->where('expires_at', '>', Carbon::now()) ->first(); return $accessToken; } /** * 撤销访问令牌 */ public static function revokeToken(string $accessToken): bool { return OAuthAccessToken::where('access_token', $accessToken)->delete() > 0; } /** * 获取客户端信息 */ public static function getClient(string $clientId): ?OAuthClient { return OAuthClient::where('client_id', $clientId)->first(); } /** * 获取用户的所有访问令牌 */ public static function getUserTokens(int $userId): array { return OAuthAccessToken::where('user_id', $userId) ->where('expires_at', '>', now()) ->get() ->toArray(); } /** * 获取客户端的所有访问令牌 */ public static function getClientTokens(string $clientId): array { return OAuthAccessToken::where('client_id', $clientId) ->where('expires_at', '>', now()) ->get() ->toArray(); } /** * 清理过期的令牌 */ public static function cleanExpiredTokens(): int { return OAuthAccessToken::where('expires_at', '<=', now())->delete(); } }