tencent cloud

Serverless Cloud Function

ドキュメントServerless Cloud FunctionUser GuideFunction URLFunction URL Authentication and Authorization Configuration

Function URL Authentication and Authorization Configuration

PDF
フォーカスモード
フォントサイズ
最終更新日: 2025-06-17 16:41:25

Overview

You can control access to the function URL by configuring an authentication and certification policy.
When configuring the function URL, you must specify one of the following authentication options:
CAM Authentication: Authentication validation is required for the function. Users can perform resource management and usage rights configuration through the function InvokeFunctionUrl interface. You can open or restrict access to the interface by configuring InvokeFunctionUrl policy permissions.
Open: No identity verification is required for function requests. Anonymous access is supported. Anyone can initiate an HTTP request to call your function.

Configure InvokeFunctionUrl Policy Permissions

You can refer to the following steps to configure InvokeFunctionUrl policy permissions to open or restrict access to the interface.
1. On the Policy page of the cloud access management console , click Create Custom Policy in the upper left corner.
2. In the pop - up window for selecting creation method, click create by policy generator to enter the edit strategy page.
3. In the Visual Strategy Generator, add a service and operation column, add the following information, and edit an authorization statement.
Effect (required): Select Allow.
Service (required): Select Serverless Cloud Function (scf).
Operation (required): Click Expand on the right of all operations (scf:*), search for InvokeFunctionUrl, and check it. As shown below:

Resource (required): Select all resources or the specific resource you want to authorize.
Condition (optional): Set the effective condition for the above authorization.
4. Complete the policy authorization statement editing, then click Next to enter the basic information and associated users/groups/roles page.
5. On the associated users/groups/roles page, add the policy name and description, and you can simultaneously associate users/groups/roles for quick authorization.
6. Click Finish to complete the operation of creating a custom policy using the policy generator.

Signature Generation and Authentication Process

Client-Side Signature Generation

signature algorithm: please see Signature Method of Security Credential Service. Sample code is as follows:
Java
Go
NodeJS
Python
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class TencentCloudAPITC3Demo {
private final static Charset UTF8 = StandardCharsets.UTF_8;
// The environment variable TENCENTCLOUD_SECRET_ID needs to be set, with the value being the example AKID***************
private final static String SECRET_ID = System.getenv("TENCENTCLOUD_SECRET_ID");
// The environment variable TENCENTCLOUD_SECRET_KEY needs to be set, with the value being the example Gu5t9xGARNpq86cd98joQYCN3*******
private final static String SECRET_KEY = System.getenv("TENCENTCLOUD_SECRET_KEY");
private final static String CT_JSON = "application/json";

public static byte[] hmac256(byte[] key, String msg) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
mac.init(secretKeySpec);
return mac.doFinal(msg.getBytes(UTF8));
}

public static String sha256Hex(String s) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] d = md.digest(s.getBytes(UTF8));
return DatatypeConverter.printHexBinary(d).toLowerCase();
}

public static void main(String[] args) throws Exception {
String service = "scf";
String host = "1253970226-xxxxxxx-cq.scf.tencentcs.com";
String uin = "xxxxxx"; // Replace with the actual uin to be used
String algorithm = "TC3-HMAC-SHA256";
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Note the time zone, otherwise errors are likely to occur.
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String date = sdf.format(new Date(Long.valueOf(timestamp + "000")));

// ************* Step 1: Construct standard request string *************
String httpRequestMethod = "POST";
String canonicalUri = "/";
String canonicalQueryString = "";
String canonicalHeaders = "content-type:application/json; charset=utf-8\\n"
+ "host:" + host + "\\n" ;
String signedHeaders = "content-type;host";

// Request body
String payload = "{\\"Limit\\": 1, \\"Filters\\": [{\\"Values\\": [\\"\\\\u672a\\\\u547d\\\\u540d\\"], \\"Name\\": \\"instance-name\\"}]}";
String hashedRequestPayload = sha256Hex(payload);
String canonicalRequest = httpRequestMethod + "\\n" + canonicalUri + "\\n" + canonicalQueryString + "\\n"
+ canonicalHeaders + "\\n" + signedHeaders + "\\n" + hashedRequestPayload;
System.out.println(canonicalRequest);

// ************* Step 2: Concatenate strings to be signed *************
String credentialScope = date + "/" + service + "/" + "tc3_request";
String hashedCanonicalRequest = sha256Hex(canonicalRequest);
String stringToSign = algorithm + "\\n" + timestamp + "\\n" + credentialScope + "\\n" + hashedCanonicalRequest;
System.out.println(stringToSign);

// ************* Step 3: Calculate the signature *************
byte[] secretDate = hmac256(("TC3" + SECRET_KEY).getBytes(UTF8), date);
byte[] secretService = hmac256(secretDate, service);
byte[] secretSigning = hmac256(secretService, "tc3_request");
String signature = DatatypeConverter.printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();
System.out.println(signature);

// ************* Step 4: Concatenate Authorization *************
String authorization = algorithm + " " + "Credential=" + SECRET_ID + "/" + credentialScope + ", "
+ "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature;
System.out.println(authorization);


StringBuilder sb = new StringBuilder();
sb.append("curl -X POST https://").append(host+canonicalUri)
.append(" -H \\"Authorization: ").append(authorization).append("\\"")
.append(" -H \\"Content-Type: application/json; charset=utf-8\\"")
.append(" -H \\"Host: ").append(host).append("\\"")
.append(" -H \\"X-Scf-Cam-Uin: ").append(uin).append("\\"")
.append(" -H \\"X-Scf-Cam-Timestamp: ").append(timestamp).append("\\"")
.append(" -d '").append(payload).append("'");
System.out.println(sb.toString());
}
}
package main

import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"time"
)

func sha256hex(s string) string {
b := sha256.Sum256([]byte(s))
return hex.EncodeToString(b[:])
}

func hmacsha256(s, key string) string {
hashed := hmac.New(sha256.New, []byte(key))
hashed.Write([]byte(s))
return string(hashed.Sum(nil))
}

func main() {
// need to fill in account UIN
uin := "xxxx"
// The environment variable TENCENTCLOUD_SECRET_ID needs to be set, with the value being the example AKID***************
secretId := os.Getenv("TENCENTCLOUD_SECRET_ID")
// The environment variable TENCENTCLOUD_SECRET_KEY needs to be set, with the value being the example Gu5t9xGARNpq86cd98joQYCN3*******
secretKey := os.Getenv("TENCENTCLOUD_SECRET_KEY")
host := "1253970226-xxxxxxx-cq.scf.tencentcs.com"

algorithm := "TC3-HMAC-SHA256"
service := "scf"
var timestamp int64 = time.Now().Unix()

// step 1: build canonical request string
httpRequestMethod := "POST"
canonicalURI := "/"
canonicalQueryString := ""
canonicalHeaders := fmt.Sprintf("content-type:%s\\nhost:%s\\n",
"application/json", host)
signedHeaders := "content-type;host"
payload := `{"Limit": 1, "Filters": [{"Values": ["\\u672a\\u547d\\u540d"], "Name": "instance-name"}]}`
hashedRequestPayload := sha256hex(payload)
canonicalRequest := fmt.Sprintf("%s\\n%s\\n%s\\n%s\\n%s\\n%s",
httpRequestMethod,
canonicalURI,
canonicalQueryString,
canonicalHeaders,
signedHeaders,
hashedRequestPayload)
fmt.Println("canonicalRequest => ", canonicalRequest)

// step 2: build string to sign
date := time.Unix(timestamp, 0).UTC().Format("2006-01-02")
credentialScope := fmt.Sprintf("%s/%s/tc3_request", date, service)
hashedCanonicalRequest := sha256hex(canonicalRequest)
string2sign := fmt.Sprintf("%s\\n%d\\n%s\\n%s",
algorithm,
timestamp,
credentialScope,
hashedCanonicalRequest)
fmt.Println("string2sign ==>", string2sign)

// step 3: sign string
secretDate := hmacsha256(date, "TC3"+secretKey)
secretService := hmacsha256(service, secretDate)
secretSigning := hmacsha256("tc3_request", secretService)
signature := hex.EncodeToString([]byte(hmacsha256(string2sign, secretSigning)))
fmt.Println(signature)

// step 4: build authorization
authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",
algorithm,
secretId,
credentialScope,
signedHeaders,
signature)
fmt.Println(authorization)

curl := fmt.Sprintf(`curl -X %s https://%s -H "Authorization: %s" -H "Content-Type: application/json" -H "Host: %s" -H "X-Scf-Cam-Uin: %s" -H "X-Scf-Cam-Timestamp: %d" -d '%s'`,
httpRequestMethod, host, authorization, host, uin, timestamp, payload)
fmt.Println(curl)
}
const crypto = require('crypto');

function sha256(message, secret = '', encoding) {
const hmac = crypto.createHmac('sha256', secret)
return hmac.update(message).digest(encoding)
}

function getHash(message, encoding = 'hex') {
const hash = crypto.createHash('sha256')
return hash.update(message).digest(encoding)
}

function getDate(timestamp) {
const date = new Date(timestamp * 1000)
const year = date.getUTCFullYear()
const month = ('0' + (date.getUTCMonth() + 1)).slice(-2)
const day = ('0' + date.getUTCDate()).slice(-2)
return `${year}-${month}-${day}`
}

function main(){
// key parameters
// The environment variable TENCENTCLOUD_SECRET_ID needs to be set, with the value being the example AKID***************
const SECRET_ID = process.env.TENCENTCLOUD_SECRET_ID
// The environment variable TENCENTCLOUD_SECRET_KEY needs to be set, with the value being the example Gu5t9xGARNpq86cd98joQYCN3*******
const SECRET_KEY = process.env.TENCENTCLOUD_SECRET_KEY

const endpoint = "1253970226-xxxxxxx-cq.scf.tencentcs.com"
const service = "scf"
const timestamp = getTime()
// Time processing, get the world date and time
const date = getDate(timestamp)

// ************* Step 1: Construct standard request string *************
const payload = "{\\"Limit\\": 1, \\"Filters\\": [{\\"Values\\": [\\"\\\\u672a\\\\u547d\\\\u540d\\"], \\"Name\\": \\"instance-name\\"}]}"

const hashedRequestPayload = getHash(payload);
const httpRequestMethod = "POST"
const canonicalUri = "/"
const canonicalQueryString = ""
const canonicalHeaders = "content-type:application/json\\n"
+ "host:" + endpoint + "\\n"
const signedHeaders = "content-type;host"

const canonicalRequest = httpRequestMethod + "\\n"
+ canonicalUri + "\\n"
+ canonicalQueryString + "\\n"
+ canonicalHeaders + "\\n"
+ signedHeaders + "\\n"
+ hashedRequestPayload
console.log(canonicalRequest)

// ************* Step 2: Concatenate strings to be signed *************
const algorithm = "TC3-HMAC-SHA256"
const hashedCanonicalRequest = getHash(canonicalRequest);
const credentialScope = date + "/" + service + "/" + "tc3_request"
const stringToSign = algorithm + "\\n" +
timestamp + "\\n" +
credentialScope + "\\n" +
hashedCanonicalRequest
console.log(stringToSign)

// ************* Step 3: Calculate the signature *************
const kDate = sha256(date, 'TC3' + SECRET_KEY)
const kService = sha256(service, kDate)
const kSigning = sha256('tc3_request', kService)
const signature = sha256(stringToSign, kSigning, 'hex')
console.log(signature)

// ************* Step 4: Concatenate Authorization *************
const authorization = algorithm + " " +
"Credential=" + SECRET_ID + "/" + credentialScope + ", " +
"SignedHeaders=" + signedHeaders + ", " +
"Signature=" + signature
console.log(authorization)

const curlcmd = 'curl -X POST ' + "https://" + endpoint
+ ' -H "Authorization: ' + authorization + '"'
+ ' -H "Content-Type: application/json"'
+ ' -H "Host: ' + endpoint + '"'
+ ' -H "X-Scf-Cam-Uin: ' + uin + '"'
+ ' -H "X-Scf-Cam-Timestamp: ' + timestamp.toString() + '"'
+ " -d '" + payload + "'"
console.log(curlcmd)
}
main()
# -*- coding: utf-8 -*-
import hashlib, hmac, json, os, sys, time
from datetime import datetime

# Key parameters
# The environment variable TENCENTCLOUD_SECRET_ID needs to be set, with the value being the example AKID**************
secret_id = os.environ.get("TENCENTCLOUD_SECRET_ID")
# The environment variable TENCENTCLOUD_SECRET_KEY needs to be set, with the value being the example Gu5t9xGARNpq86cd98joQYCN3*******
secret_key = os.environ.get("TENCENTCLOUD_SECRET_KEY")

service = "scf"
host = "1253970226-xxxxxxx-cq.scf.tencentcs.com"
endpoint = "https://" + host
algorithm = "TC3-HMAC-SHA256"
timestamp = int(time.time())
date = datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d")
params = {"Limit": 1, "Filters": [{"Values": ["unnamed"], "Name": "instance-name"}]}

# ************* Step 1: Concatenate specification request strings *************
http_request_method = "POST"
canonical_uri = "/"
canonical_querystring = ""
ct = "application/json"
payload = json.dumps(params)
canonical_headers = "content-type:%s\\nhost:%s\\n" % (ct, host)
signed_headers = "content-type;host"
hashed_request_payload = hashlib.sha256(payload.encode("utf-8")).hexdigest()
canonical_request = (http_request_method + "\\n" +
canonical_uri + "\\n" +
canonical_querystring + "\\n" +
canonical_headers + "\\n" +
signed_headers + "\\n" +
hashed_request_payload)
print(canonical_request)

# ************* Step 2: Concatenate strings to be signed *************
credential_scope = date + "/" + service + "/" + "tc3_request"
hashed_canonical_request = hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()
string_to_sign = (algorithm + "\\n" +
str(timestamp) + "\\n" +
credential_scope + "\\n" +
hashed_canonical_request)
print(string_to_sign)


# ************* Step 3 Calculate the signature *************
# Calculate signature digest function
def sign(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
secret_date = sign(("TC3" + secret_key).encode("utf-8"), date)
secret_service = sign(secret_date, service)
secret_signing = sign(secret_service, "tc3_request")
signature = hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
print(signature)

#************Step 4: Concatenate Authorization *************
authorization = (algorithm + " " +
"Credential=" + secret_id + "/" + credential_scope + ", " +
"SignedHeaders=" + signed_headers + ", " +
"Signature=" + signature)
print(authorization)

print('curl -X POST ' + endpoint
+ ' -H "Authorization: ' + authorization + '"'
+ ' -H "Content-Type: application/json"'
+ ' -H "Host: ' + host + '"'
+ ' -H "X-Scf-Cam-Uin: ' + uin + '"'
+ ' -H "X-Scf-Cam-Timestamp: ' + str(timestamp) + '"'
+ " -d '" + payload + "'")
algorithm := "TC3-HMAC-SHA256"
service := "scf"
var timestamp int64 = time.Now().Unix()

// step 1: build canonical request string
httpRequestMethod := "POST"
canonicalURI := "/"
canonicalQueryString := ""
canonicalHeaders := fmt.Sprintf("content-type:%s\\nhost:%s\\n",
"application/json", host)
signedHeaders := "content-type;host"
payload := `{"Limit": 1, "Filters": [{"Values": ["\\u672a\\u547d\\u540d"], "Name": "instance-name"}]}`
hashedRequestPayload := sha256hex(payload)
canonicalRequest := fmt.Sprintf("%s\\n%s\\n%s\\n%s\\n%s\\n%s",
httpRequestMethod,
canonicalURI,
canonicalQueryString,
canonicalHeaders,
signedHeaders,
hashedRequestPayload)
fmt.Println("canonicalRequest => ", canonicalRequest)

// step 2: build string to sign
date := time.Unix(timestamp, 0).UTC().Format("2006-01-02")
credentialScope := fmt.Sprintf("%s/%s/tc3_request", date, service)
hashedCanonicalRequest := sha256hex(canonicalRequest)
string2sign := fmt.Sprintf("%s\\n%d\\n%s\\n%s",
algorithm,
timestamp,
credentialScope,
hashedCanonicalRequest)
fmt.Println("string2sign ==>", string2sign)

// step 3: sign string
secretDate := hmacsha256(date, "TC3"+secretKey)
secretService := hmacsha256(service, secretDate)
secretSigning := hmacsha256("tc3_request", secretService)
signature := hex.EncodeToString([]byte(hmacsha256(string2sign, secretSigning)))
fmt.Println(signature)

// step 4: build authorization
authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",
algorithm,
secretId,
credentialScope,
signedHeaders,
signature)
fmt.Println(authorization)

curl := fmt.Sprintf(`curl -X %s https://%s -H "Authorization: %s" -H "Content-Type: application/json" -H "Host: %s" -H "X-Scf-Cam-Uin: %s" -H "X-Scf-Cam-Timestamp: %d" -d '%s'`,
httpRequestMethod, host, authorization, host, uin, timestamp, payload)
fmt.Println(curl)

Client Call Parameters

The following parameters need to be added in the Header of the URL request.
Parameter
Description
Authorization
Signature-related parameters, required. Example:
TC3-HMAC-SHA256 Credential=AKID****************/2019-02-25/scf/tc3_request, SignedHeaders=content-type;host;xxx, Signature=be4f67d323c78ab9acb7395e43c0dbcf822a9cfac32fea2449a7bc7726b770a3
X-Scf-Cam-Timestamp
Timestamp used for signature generation, required.
X-Scf-Cam-Uin
Root account Uin, required.
X-Scf-Cam-Token
If generating a signature using a temporary key, token information is required.

Server-Side Signature Verification

Server invocation of CAM service's signature and authentication, please see Cloud Access Management.



ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック