SMS Extension (EasyAdminBlazor.Sms)

One unified ISmsService for template SMS across Aliyun (domestic SendSms), Tencent Cloud, and SendCloud. It picks a provider automatically or by explicit configuration, persists send results for auditing, and ships an OTP service. Each provider speaks its own HTTP protocol with signatures computed in-extension — no official SDKs are referenced.

Overview

  • One interface, three providers: Auto picks the first fully configured provider (Aliyun → Tencent → SendCloud), or specify one explicitly
  • Plain HTTP with self-computed signatures: Aliyun RPC HMAC-SHA1, Tencent TC3-HMAC-SHA256, SendCloud MD5; no official SDK dependency
  • ISmsService.SendAsync accepts multiple phone numbers and a dictionary of named template variables, and returns the provider plus platform error codes
  • The legacy SendSmsAsync signature remains compatible, so custom ISmsService implementations that only implement the old method (including the old AliyunSms extension) keep working
  • Keys can be maintained in the admin "System Settings" page (Secret fields are encrypted at rest and never echoed back; saves take effect immediately)
  • Send results, including failures, are written to SysSmsLog for auditing and abuse investigation; disable with Sms:EnableLogging
  • SmsCodeService provides OTP generation, verification and three layers of abuse protection (send interval, hourly count, TTL; each code is consumed once)
  • Tencent/Huawei-style array template variables are expanded in ordinal dictionary order of variable names

Installation and Registration

builder.AddEasyAdminBlazor(new EasyAdminBlazorOptions { ... })
    .AddEasyAdminBlazorSms();

An IServiceCollection overload is also available:

services.AddEasyAdminBlazorSms(configuration);

What gets registered:

  • A named HttpClient "EasyAdminBlazor.Sms" with a 10-second timeout
  • Three ISmsSender singletons (Aliyun, Tencent, SendCloud)
  • ISmsService replaced by SmsService (scoped)
  • SmsCodeService (scoped)
  • SmsConfigSettingsContributor (scoped), contributing SMS settings to the admin "System Settings" page
  • Registration of the extension assembly: adds SysSmsLog to the shared-database table list for hybrid multi-tenancy (dedicated databases create it on first access, the main database uses SmsInitializer, and a shared database with a custom connection string relies on this registration)

Without this extension, calls to the framework's default ISmsService throw a guidance exception telling you to reference EasyAdminBlazor.Sms and call AddEasyAdminBlazorSms().

Configuration

The Sms section in appsettings

Full example (all three credentials are shown; fill in only the provider you use):

{
  "Sms": {
    "Provider": "Auto",
    "Aliyun": {
      "AccessKeyId": "your_access_key_id",
      "AccessKeySecret": "your_access_key_secret",
      "SignName": "your_sign_name"
    },
    "Tencent": {
      "SecretId": "your_secret_id",
      "SecretKey": "your_secret_key",
      "SdkAppId": "1400000000",
      "SignName": "your_sign_name",
      "Region": "ap-guangzhou"
    },
    "SendCloud": {
      "SmsUser": "your_sms_user",
      "SmsKey": "your_sms_key",
      "Tag": ""
    },
    "EnableLogging": true,
    "Code": {
      "TemplateCode": "SMS_xxxx",
      "Length": 6,
      "TtlMinutes": 10,
      "SendIntervalSeconds": 60,
      "HourlyLimit": 10
    }
  }
}

Values for Sms:Provider:

Value Meaning
Auto (default) Check Aliyun → Tencent → SendCloud in order and use the first with complete parameters
Aliyun Aliyun SMS only (dysmsapi, domestic SendSms)
Tencent Tencent Cloud SMS only (sms, SendSms)
SendCloud SendCloud SMS only (smsapi/send)

If you explicitly select a provider but its parameters are incomplete, it is treated as not configured: SendAsync returns a failure result with the NotConfigured error code, with no silent fallback to another provider.

Provider-specific fields:

Group Field Default Description
Aliyun AccessKeyId empty Aliyun AccessKey ID
Aliyun AccessKeySecret empty Aliyun AccessKey Secret
Aliyun SignName empty Sign name registered in the console
Tencent SecretId empty Tencent Cloud SecretId
Tencent SecretKey empty Tencent Cloud SecretKey
Tencent SdkAppId empty SMS application SdkAppId
Tencent SignName empty Sign content, without 【】 brackets
Tencent Region ap-guangzhou Region
SendCloud SmsUser empty SMS product-line account, independent of the mail apiUser
SendCloud SmsKey empty SMS product-line key, independent of the mail apiKey
SendCloud Tag empty Optional tag for statistics grouping in the SendCloud console

Aliyun is considered configured only when AccessKeyId + AccessKeySecret + SignName are all set; Tencent requires SecretId + SecretKey + SdkAppId + SignName; SendCloud requires SmsUser + SmsKey.

Top-level and OTP fields:

Field Default Description
EnableLogging true Whether to persist send results (including failures) to SysSmsLog; SMS costs money and needs auditing, so keep it on
Code:TemplateCode empty OTP template ID; the template must contain a numeric variable
Code:Length 6 Number of OTP digits
Code:TtlMinutes 10 OTP validity in minutes
Code:SendIntervalSeconds 60 Minimum interval between two sends to the same number, in seconds
Code:HourlyLimit 10 Maximum sends per hour to the same number

Configuration comes from two places: the Sms section and Sms:* keys saved in the admin "System Settings" page, with the latter taking precedence. Settings are read from IConfiguration on every send, so admin saves take effect immediately without a restart. Secret fields saved in the admin page are AES ciphertext, decrypted on read with EasyAdminBlazorOptions.AesKey (legacy plaintext is still accepted). The same key must be used for saving and reading, otherwise the decrypted value is still ciphertext — and the provider will appear misconfigured.

Admin settings page fields

The SMS section of "System Settings" is contributed by SmsConfigSettingsContributor (ConfigType is Sms):

Config key Display name Control Notes
Sms:Provider Provider Select Aliyun / Tencent / SendCloud
Sms:Aliyun:AccessKeyId Aliyun AccessKeyId Text
Sms:Aliyun:AccessKeySecret Aliyun AccessKeySecret Secret AES encrypted at rest, not echoed
Sms:Aliyun:SignName Aliyun Sign Name Text Sign name registered in the console
Sms:Tencent:SecretId Tencent SecretId Text
Sms:Tencent:SecretKey Tencent SecretKey Secret AES encrypted at rest, not echoed
Sms:Tencent:SdkAppId Tencent SdkAppId Text SMS application ID, e.g. 1400000000
Sms:Tencent:SignName Tencent Sign Name Text Without 【】 brackets
Sms:Tencent:Region Tencent Region Text Defaults to ap-guangzhou
Sms:SendCloud:SmsUser SendCloud SmsUser Text
Sms:SendCloud:SmsKey SendCloud SmsKey Secret AES encrypted at rest, not echoed
Sms:SendCloud:Tag SendCloud Tag Text Optional, for statistics grouping
Sms:Code:TemplateCode OTP template ID Text Used by SmsCodeService
Sms:Code:Length OTP length Integer Defaults to 6
Sms:Code:TtlMinutes OTP validity (minutes) Integer Defaults to 10

Notes:

  • Secret fields are encrypted and never echoed back; not seeing the original value after a refresh is expected, not a lost setting.
  • Sms:Code:SendIntervalSeconds, Sms:Code:HourlyLimit and Sms:EnableLogging are not in the page's field list. To change them, set them in the Sms section of appsettings.
  • The page shows only the selected provider's private fields: pick a provider in the dropdown and only its parameters appear. While left at Auto, it picks a provider based on which fields are filled in (Aliyun if none are). This is page rendering behavior only; Auto on the send side is unaffected.
  • Length and TtlMinutes are seeded with defaults 6 / 10 when the rows are missing. Values already saved by an administrator always win.

Sending SMS

Inject ISmsService and use the new SendAsync method:

@inject ISmsService SmsService

var result = await SmsService.SendAsync(new SmsSendRequest
{
    PhoneNumbers = new[] { "13800000000" },
    TemplateCode = "SMS_123456",
    TemplateParams = new Dictionary<string, string>
    {
        ["code"] = "1234",
        ["expire"] = "10",
    },
});

if (!result.Success)
{
    // result.ErrorCode / result.ErrorMessage come from the platform
}

SmsSendRequest fields:

Field Description
PhoneNumbers Recipient list; 11-digit domestic numbers without prefixes. Provider-specific prefixes are added internally
TemplateCode Template ID: Aliyun SMS_xxxxxxxx, Tencent template ID, SendCloud numeric template ID
TemplateParams Dictionary of named template variables; pass null or an empty dictionary for templates without variables
SessionContext Opaque session identifier passed through to the platform (e.g. Tencent SessionContext) for delivery correlation; mapped to OutId on Aliyun and custom on SendCloud; optional

SmsSendResult fields:

Field Description
Success Whether sending succeeded
Provider Provider actually used (aliyun / tencent / sendcloud; custom when forwarded by a custom implementation)
ErrorCode Raw platform error code (Aliyun isv.*, Tencent Ok/error code, SendCloud statusCode; NotConfigured when not configured, RequestFailed on request exceptions)
ErrorMessage Platform error message, safe to display directly to users

The legacy signature remains compatible:

var ok = await SmsService.SendSmsAsync("13800000000", "SMS_123456", "{\"code\":\"1234\"}");

templateParam must be a JSON object string, and multiple numbers are comma-separated. It is converted into an SmsSendRequest and dispatched to SendAsync, returning only a bool. The interface also provides a default implementation: a custom ISmsService that only implements the old method needs no changes — the new method forwards to it and serializes template variables to JSON. New code should use SendAsync.

OTP Codes

SmsCodeService wraps generation, sending, verification and abuse protection:

@inject SmsCodeService SmsCodeService

// Send: null means sent; otherwise the returned error message can be shown directly
var error = await SmsCodeService.SendCodeAsync("13800000000");

// Verify: true only when correct and not expired; the code is consumed immediately afterwards (replay protection)
var valid = SmsCodeService.VerifyCode("13800000000", userInput);

Before sending, it checks Sms:Code:TemplateCode; without a configured template it returns an error without calling the platform. The template must contain numeric variables; sending passes code (the OTP) and expire (validity in minutes). Codes are generated with a cryptographic random number generator.

Three abuse-protection layers, mapped to configuration:

Config Default Effect
Sms:Code:SendIntervalSeconds 60 seconds Minimum interval between sends to the same number; faster requests are rejected
Sms:Code:HourlyLimit 10 Maximum sends per hour to the same number; the counter resets when the window passes
Sms:Code:TtlMinutes 10 minutes OTP validity; verification fails after expiry

Codes live only in memory (a ConcurrentDictionary, single-instance semantics) and are lost on restart; multi-instance deployments need to replace this class with a Redis-backed implementation. Sending and verification do not depend on SysSmsLog; whether a send is logged is still controlled by Sms:EnableLogging.

Send Log

When EnableLogging is on (the default), every send — including failures — writes a SysSmsLog row for auditing and abuse investigation. A logging failure writes an error log but does not affect the send result.

Field Description
TenantCode Tenant code; row-level isolation under hybrid multi-tenancy
PhoneNumbers Recipients, comma-separated
TemplateCode Template ID
TemplateParams Template variables as JSON
Provider Provider
Success Whether sending succeeded (accepted by the platform)
ErrorCode / ErrorMessage Platform error code and message
ElapsedMs Send duration in milliseconds

Records also carry the creation timestamp and other EntityCreated fields. SMS is billed per message, so keep logging enabled.

Template Variable Ordering

Tencent and Huawei-style platforms take template parameters as an array with no variable names. The extension expands them in ordinal dictionary order of the variable names (StringComparer.Ordinal). For example, the code and expire variables passed by SmsCodeService are expanded in that order. Name template variables in dictionary order (e.g. a, b, c), otherwise array positions will not match the placeholders in the template. Aliyun and SendCloud take named-variable JSON and are unaffected by this convention.

Migration and Multi-Tenancy

  • The old EasyAdminBlazor.AliyunSms extension is no longer maintained. Use this extension for new projects. Existing projects can keep the old extension (the interface's default forwarding keeps it working) and migrate to AddEasyAdminBlazorSms() gradually.
  • SmsConfigSettingsContributor seeds SysConfig rows into the current database on construction. Under multi-tenancy the injected IFreeSql is scoped to the tenant database, so each tenant seeds its own copy and the admin page saves values into the current tenant's database. The contributor is therefore registered as scoped (as in the Mail extension) to avoid a lifetime validation error at startup.
  • SysSmsLog implements ITenantEntity, and its TenantCode participates in row-level isolation, so SMS records are isolated per tenant.