Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Credentials Laravel Package

alibabacloud/credentials

Alibaba Cloud Credentials for PHP offers flexible credential providers for Alibaba Cloud SDKs, supporting AccessKey, STS tokens, RAM roles, environment variables, and config files with automatic refresh and simple integration.

View on GitHub
Deep Wiki
Context7

Getting Started

alibabacloud/credentials is not a cloud client — it is the credential-provider layer that sits underneath alibabacloud/darabonba-openapi and every alibabacloud/* SDK. You rarely install it on purpose; you install it when you want credential resolution (env vars, STS, RAM roles, instance metadata) decoupled from the client that consumes it. With ~4 stars and 0 declared dependents on GitHub it looks abandoned; in practice it is pulled in transitively by thousands of projects, so treat the star count as noise and judge it by the SDKs that pin it.

Install and first use case

composer require alibabacloud/credentials

The first thing to do is delete hard-coded keys from your codebase and resolve them through a Credential:

use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Credentials\Credential\Config;

$credential = new Credential(new Config([
    'type'            => 'access_key',
    'accessKeyId'     => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
]));

$client = new \AlibabaCloud\SDK\Ecs\V20140526\Ecs(new \Darabonba\OpenApi\Models\Config([
    'credential' => $credential,          // pass the object, not the strings
    'endpoint'   => 'ecs.cn-hangzhou.aliyuncs.com',
]));

Where to look first

  1. src/Credential/Config.php — this is the real API surface. Every supported type (access_key, sts, ecs_ram_role, ram_role_arn, rsa_key_pair, bearer, and whatever your version adds) and every field it accepts is declared here as typed properties. Read this file before reading the README.
  2. src/Providers/ — one class per type. This is where the actual STS AssumeRole call, the ECS metadata GET, and the refresh logic live. If a credential type misbehaves, debug here.
  3. tests/ — the only reliable source of working config arrays, since the README lags the code.

Implementation Patterns

Pick the provider by deployment target, not by preference. The type string is the only thing that should change between environments:

Environment type Secrets on disk
Local dev / CI access_key env vars only
ECS / ACK pod with RAM role ecs_ram_role none
Cross-account or scoped access ram_role_arn one long-lived AK, or an ecs_ram_role source
Credentials minted by your own auth service sts the token you already hold
Legacy RSA-signed APIs rsa_key_pair private key file

Pattern: build once, inject everywhere. A Credential is stateful and self-refreshing — it holds an expiry timestamp and re-fetches when a getter is called past the threshold. Constructing one per request throws that away and, for ram_role_arn/ecs_ram_role, means an STS or metadata round-trip on every request.

// app/Providers/AlibabaCloudServiceProvider.php
public function register(): void
{
    $this->app->singleton(Credential::class, function () {
        return new Credential(new Config([
            'type'                  => config('alibaba.credential_type'), // 'ecs_ram_role' in prod
            'roleName'              => config('alibaba.role_name'),
            'accessKeyId'           => config('alibaba.ak'),
            'accessKeySecret'       => config('alibaba.sk'),
            'roleArn'               => config('alibaba.role_arn'),
            'roleSessionName'       => 'app-' . gethostname(),
            'roleSessionExpiration' => 3600,
        ]));
    });
}

Then inject Credential into whatever builds your SDK clients. This single binding is what makes the rest of the library worth using: swapping from static AK to instance role in production becomes a config change, not a code change.

Pattern: scoped role assumption. For anything touching user data, don't run with the role's full permissions. Pass a policy to narrow the session:

'type'     => 'ram_role_arn',
'roleArn'  => 'acs:ram::1234567890:role/app-reader',
'policy'   => json_encode([
    'Version'   => '1',
    'Statement' => [[
        'Effect'   => 'Allow',
        'Action'   => ['oss:GetObject'],
        'Resource'=> ['acs:oss:*:1234567890:my-bucket/reports/*'],
    ]],
]),
'roleSessionExpiration' => 900, // short-lived by design

Because the provider refreshes automatically, a 900-second session costs you nothing in code — but it does mean the assumed role must still exist and the policy must still be valid at refresh time. Rotate/delete roles carefully in production.

Pattern: STS passthrough. When your own backend already brokers credentials (a token-vending service, a CI OIDC exchange, a multi-tenant gateway), wrap the returned triple in type => 'sts' and let the SDK consume it. This is the cleanest seam if you don't want applications holding long-lived keys at all.

Pattern: keep the credential object out of your domain layer. Wrap it:

final class CloudStorage
{
    public function __construct(private Credential $credential) {}

    public function client(): OssClient
    {
        return new OssClient(new Config([
            'credential' => $this->credential,
            'endpoint'   => 'oss-cn-hangzhou.aliyuncs.com',
        ]));
    }
}

Now every test can inject a fake that satisfies the same getters, and nothing outside this class knows what type you're running.

Gotchas and Tips

Never log, dd(), dump(), or json_encode() a Credential or Config. Both are array-serializable and will happily print your accessKeySecret and securityToken into Laravel's log, Telescope, Sentry, or an exception payload. If you need observability, log $credential->getType() and nothing else, and add a scrubber for accessKeySecret / securityToken keys.

Long-running workers and Octane are the happy path — but watch the refresh. A singleton Credential refreshing lazily is exactly right for queue workers and Octane. Under Swoole coroutine concurrency, though, N coroutines can hit an expired credential simultaneously and each fire an AssumeRole call. If STS rate limits bite you, wrap the credential in a small cache/coroutine-local lock, or pre-warm it on a timer.

ECS metadata is a network call with a real fail mode. ecs_ram_role blocks on 100.100.100.200. In a container without IMDS access, behind a proxy, or on a laptop, the first getter call hangs or throws. Never construct this provider in a service-provider boot() or in middleware that runs on every request — build it lazily, and in dev config default to access_key. Recent versions support the IMDSv2 token handshake; older ones silently use v1 and can fail on instances with v2 enforced.

getSecurityToken() returns '' for non-STS types, not null. Code doing if ($cred->getSecurityToken() !== null) will then pass an empty x-acs-security-token header and get a confusing InvalidAccessKeyId/signature error. Check !== ''.

Clock skew breaks temporary credentials in a way that looks like a permissions bug. Expiry is evaluated against local time. On a VM with drift you'll get intermittent InvalidSecurityToken after a refresh, or a refresh that never triggers. Run NTP, and give yourself margin by using the roleSessionExpiration ceiling rather than assuming the full window.

Env var names are a hard convention, not a suggestion: ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, ALIBABA_CLOUD_SECURITY_TOKEN, ALIBABA_CLOUD_ROLE_ARN, ALIBABA_CLOUD_OIDC_TOKEN_FILE. Getting one wrong usually means an empty string is passed to Config and you get a cryptic validation/download error rather than "missing credential". Config typed properties are nullable and lenient — validate your own config at boot and fail loudly.

The policy field is a JSON string, and it's the #1 quoting casualty. Storing multi-line JSON in .env or a Kubernetes ConfigMap and having a shell or YAML layer eat the quotes produces AssumeRole errors that don't mention the policy. Build it with json_encode() in PHP or store it base64-encoded and decode at boot.

Unknown type values and unknown Config keys don't always throw. Darabonba-style models often accept arbitrary keys. A typo like 'access_key_id' (snake_case) instead of 'accessKeyId' can leave you with empty credentials and a downstream auth failure. Pin the config array in one place and assert non-empty getters in a smoke test.

Pin the version and integration-test the credential path. Release metadata shows ongoing releases while the repo has almost no community scrutiny — a bad provider change will only surface at runtime, in the code path that runs first and least often in CI. Tag an exact minor, and add one staging test that actually resolves credentials and calls a cheap API (e.g. DescribeRegions) end-to-end.

Extension point: write your own provider. If you broker credentials from Vault, AWS Secrets Manager, or an internal service, don't contort sts — implement the provider and register the type. Keep the contract narrow (return AK/SK/token plus an expiry) so the SDK consumers stay unchanged, and make the refresh method idempotent.

Don't cache the extracted AK/SK yourself. The whole value of this package is that the strings are short-lived and the object isn't. Any place you store getAccessKeyId() in Redis, a static property, or a signed URL with a long TTL re-creates the problem the package exists to solve — cache the client, or the credential object, never the secret.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
diephp/sequences
users-au/socialite-provider
twidpay/twid-logger
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle