Using authentication methods

Updated at:

Simple identity authentication

The client program concatenates the AppCode and AppKey and adds the result to the request header or query parameters to perform identity authentication.

Parameter name

Description

Example

Date

Date in GMT format

Fri, 18 Jun 2021 07:14:23 GMT

Authorization

The caller's <AppCode><space><AppKey>

productcode 3FQoSpxUbCgz5bCss

Note

Simple identity authentication does not require additional calculations. You can initiate a request directly using the application information.

Encrypted identity authentication

The client program uses the AppKey and AppSecret to hash a set of information and generate a signature string. When you call the API, add the signature result and the key to the request header to perform identity authentication.

The encryption calculation is complex. Use the provided software development kit (SDK) and code examples to make the API calls.

Parameter Name

Description

Example

Date

Date in GMT format

Fri, 18 Jun 2021 07:14:23 GMT

signature

The calculated signature

productcode 3FQoSpxUbCgz5bCss:BwLDKVZxb6Ig7T6PdEibkWfkftFQ=

Calculation description

1) Calculate the content:
    # GET request
    ${method}\n${path}\n${date}
    # Non-GET request
    ${method}\n${path}\n${date}\n${bodyMd5}

2) Calculate the SignStr:
		Encrypt the content from step 1) using HmacSHA1 with the AppSecret as the key. Then, Base64 encode the ciphertext.

3) Calculate the signature:
		signature = AppCode<space>AppKey:SignStr
Note

If the path contains special characters, you must encode them.

Examples

a. Java application - SDK call (Recommended)

Dbus provides an SDK that encapsulates the signature calculation method for encrypted identity authentication. You can integrate the SDK into your Java application to make call requests directly. This eliminates the need to manually calculate the authentication signature and provides a fast and convenient method.

1. Add the following dependency to your application using Maven:

<dependency>
  <groupId>com.aliyun.dataq.service.dbus</groupId>
  <artifactId>dbus-sdk</artifactId>
  <version>1.0.3-SNAPSHOT</version>
</dependency>

2. Manually download the SDK and then import the dependency locally.

Download the SDK: Download SDK

Install the SDK to the local repository:

  mvn install:install-file\
    -DgroupId=com.aliyun.dataq.service.dbus\
    -DartifactId=dbus-sdk\
    -Dversion=1.0.3-SNAPSHOT\
    -Dpackaging=jar\
    -Dfile=${local_path_to_the_package}/dbus-sdk-1.0.3-SNAPSHOT-jar-with-dependencies.jar

Example of an SDK call:

public static void main(String[] args) {
    // The address of the target API
    String endpoint = "https://dataq.aliyuncs.com";
    // The path of the target API
    String path = "/yourworkspaceCode/yourAppCode/APIPath";
    // The AppCode, AppKey, and AppSecret for the authorized application or the application you selected when creating the API.
    String appCode = "yourAppCode";
    String appKey = "yourAppKey";
    String appSecret = "yourAppSecret";

    DataQService.Builder builder = new DataQService.Builder();
    builder.setPath(path);
    builder.setAppKey(appKey);
    builder.setAppSecret(appSecret);
    builder.setModuleName(appCode);

    // Add request header parameters
    Map<String, Object> headerMap = new HashMap<>();
    headerMap.put("Accept", "application/json");
    headerMap.put("Content-Type", "application/json");
    headerMap.put("h1", "");
    headerMap.put("h2", "");
    builder.addHeader(headerMap);

    // Add QueryParam parameters
    Map<String, Object> queryParam = new HashMap<>();
    queryParam.put("p1", "");
    queryParam.put("p2", "");
    builder.addQueryParam(queryParam);

    // Add RequestBody parameters
    Map<String, Object> map = new HashMap<>();
    map.put("b1", "");
    List<String> values = Arrays.asList("v1");
    map.put("b2", values);
    builder.setRequestBody(new JSONObject(map));

    // File upload
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
            .addTextBody("k1","v1")
            .addTextBody("k2","v2")
            .addBinaryBody("file", new File("/demo/2602780.txt"),  ContentType.APPLICATION_OCTET_STREAM, "2602780.txt");
    builder.setMultipartEntityBuilder(multipartEntityBuilder);

    // Set the request method
    DataQService dataQService = builder.setHttpMethod(HttpMethod.GET).build();

    // Initialize the request client
    DaasClient client = new DaasClient(endpoint);

    // Send the request
    Object httpResponse = client.invoke(dataQService, 1000000, 30);
	
	  // Return the result
    System.out.println(httpResponse);
}

b. Java application - Calculate the signature yourself

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public abstract class SignUtils {

    public static final String EMPTY_STRING_MD5;

    private static FastDateFormat DATE_FORMAT;

    static {
        DATE_FORMAT = FastDateFormat
                .getInstance("E, dd MMM yyyy HH:mm:ss z", TimeZone.getTimeZone("GMT"), Locale.UK);
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            md.update("".getBytes("UTF-8"));
            EMPTY_STRING_MD5 = Base64.encodeBase64String(md.digest());
        } catch (Exception ex) {
            throw new IllegalArgumentException(ex);
        }
    }

    public static Date parseGmtDate(String date) throws ParseException {
        return DATE_FORMAT.parse(date);
    }

    public static String formatGmtDate(Date date) {
        return DATE_FORMAT.format(date);
    }

    public static String toMd5(InputStream stream) throws Exception {
        return toMd5(stream, false);
    }

    public static String toMd5(InputStream stream, boolean parseEmptyStream) throws Exception {
        try {
            boolean nocontent = true;
            MessageDigest md = MessageDigest.getInstance("md5");

            int len = -1;
            byte[] buf = new byte[1024];

            while ((len = stream.read(buf)) != -1) {
                nocontent = false;
                md.update(buf, 0, len);
            }

            return nocontent ?
                    (parseEmptyStream ? EMPTY_STRING_MD5 : "") :
                    Base64.encodeBase64String(md.digest());
        } finally {
            stream.close();
        }
    }

    public static String toMd5(byte[] content) throws Exception {
        if (content == null || content.length == 0) {
            return null;
        }
        return Base64.encodeBase64String(MessageDigest.getInstance("md5").digest(content));
    }

    public static String toMd5(String content) throws Exception {
        return toMd5(content.getBytes("UTF-8"));
    }

    public static String toHmacSHA1(String data, String AppSecret) throws Exception {
        String algorithm = "HmacSHA1";
        SecretKeySpec signingKey = new SecretKeySpec(AppSecret.getBytes("UTF-8"), algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
        return Base64.encodeBase64String(rawHmac);
    }

    public static String sign4Base(String param, String salt) throws Exception {
        if (StringUtils.isEmpty(param) || StringUtils.isEmpty(salt)) {
            return null;
        }

        String query = URLDecoder.decode(param, "UTF-8");

        String[] pStr = query.trim().split("&");
        Arrays.sort(pStr);

        StringBuilder buf = new StringBuilder(salt).append(':');
        for (int i = 0; i < pStr.length; ++i) {
            buf.append(pStr[i]);
            buf.append("&");
        }
        buf.setCharAt(buf.length() - 1, ':');
        buf.append(salt);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] bytes = md.digest(buf.toString().getBytes("UTF-8"));

        return Hex.encodeHexString(bytes).toLowerCase();
    }

    private static String signedString(String method, String url, String date, String contentMd5) {
        HttpMethod hm = HttpMethod.valueOf(method.toUpperCase());
        if (hm == null) {
            throw new IllegalArgumentException("Unknow Http Method: " + method);
        }

        if (hm.needBody && contentMd5 == null) {
            contentMd5 = "";
        }
        if (contentMd5 == null) {
            StringBuilder buf = new StringBuilder(method.length() + url.length() + date.length());
            return buf.append(method).append('\n').append(url).append('\n').append(date).toString();
        }
        StringBuilder buf = new StringBuilder(
                method.length() + url.length() + date.length() + contentMd5.length());
        return buf.append(method).append('\n').append(url).append('\n').append(date).append('\n')
                .append(contentMd5).toString();
    }

    private static String doSign(String module, String appKey, String appSecret, String signedString)
            throws Exception {
        String signature = toHmacSHA1(signedString, appSecret);
        StringBuilder buf = new StringBuilder(module.length() + appKey.length() + signature.length() + 2);
        return buf.append(module).append(' ').append(appKey).append(':').append(signature).toString();
    }

    public static String originalSign4Dtboost(String appSecret, String method, String url, String gmtDate)
            throws Exception {
        return originalSign4Dtboost(appSecret, method, url, gmtDate, null);
    }

    public static String originalSign4Dtboost(String appSecret, String method, String url, String gmtDate,
                                              String contentMd5) throws Exception {
        String signedString = signedString(method, url, gmtDate, contentMd5);
        return toHmacSHA1(signedString, appSecret);
    }

    public static String sign4Dtboost(String module, String appKey, String appSecret, String method,
                                      String url, String gmtDate) throws Exception {
        return sign4Dtboost(module, appKey, appSecret, method, url, gmtDate, null);
    }

    public static String sign4Dtboost(String module, String appKey, String appSecret, String method,
                                      String url, String gmtDate, String contentMd5) throws Exception {
        String signedString = signedString(method, url, gmtDate, contentMd5);
        return doSign(module, appKey, appSecret, signedString);
    }

    public static String[] spliteSign4Dtboost(String signature) {
        int moduleIndex = signature.indexOf(' ');
        if ((moduleIndex < 1) || (moduleIndex + 3) == signature.length()) {
            return null;
        }
        int accessIdIndex = signature.indexOf(':', moduleIndex);
        if ((accessIdIndex < 2) || (accessIdIndex + 1) == signature.length()) {
            return null;
        }
        return new String[] {signature.substring(0, moduleIndex),
                signature.substring(moduleIndex + 1, accessIdIndex), signature.substring(accessIdIndex + 1)};
    }

    private static String signedString(String method, String accept, String gmtDate, String url,
                                       String contentType, String contentMd5) {
        if (accept == null) {
            accept = "";
        }
        if (contentType == null) {
            contentType = "";
        }
        if (contentMd5 == null) {
            contentMd5 = "";
        }
        method = method.toUpperCase();

        StringBuilder buf = new StringBuilder(
                method.length() + accept.length() + gmtDate.length() + url.length() + contentType.length()
                        + contentMd5.length());

        return buf.append(method).append('\n').append(accept).append('\n').append(contentMd5).append('\n')
                .append(contentType).append('\n').append(gmtDate).append('\n').append(url).toString();
    }

    public static String originalSign4Dataplus(String appSecret, String method, String accept, String gmtDate,
                                               String url) throws Exception {
        return originalSign4Dataplus(appSecret, method, accept, gmtDate, url, null, null);
    }

    public static String originalSign4Dataplus(String appSecret, String method, String accept, String gmtDate,
                                               String url, String contentType, String contentMd5) throws Exception {
        String signedString = signedString(method, accept, gmtDate, url, contentType, contentMd5);
        return toHmacSHA1(signedString, appSecret);
    }

    @Deprecated public static String sign4Datapuls(String module, String appKey, String appSecret,
                                                   String method, String accept, String gmtDate, String url) throws Exception {
        return sign4Dataplus(module, appKey, appSecret, method, accept, gmtDate, url);
    }

    public static String sign4Dataplus(String module, String appKey, String appSecret, String method,
                                       String accept, String gmtDate, String url) throws Exception {
        return sign4Dataplus(module, appKey, appSecret, method, accept, gmtDate, url, null, null);
    }

    @Deprecated public static String sign4Datapuls(String module, String appKey, String appSecret,
                                                   String method, String accept, String gmtDate, String url, String contentType, String contentMd5)
            throws Exception {
        return sign4Datapuls(module, appKey, appSecret, method, accept, gmtDate, url, contentType,
                contentMd5);
    }

    public static String sign4Dataplus(String module, String appKey, String appSecret, String method,
                                       String accept, String gmtDate, String url, String contentType, String contentMd5)
            throws Exception {
        String signedString = signedString(method, accept, gmtDate, url, contentType, contentMd5);
        return doSign(module, appKey, appSecret, signedString);
    }

    public static String[] spliteSign4Dataplus(String signature) {
        return spliteSign4Dtboost(signature);
    }

    enum HttpMethod {
        /**
         * HTTP METHOD
         */
        GET(false), POST(true), PUT(true), DELETE(false), PATCH(true), HEAD(false), OPTIONS(false), TRACE(
                false);

        private final boolean needBody;

        private HttpMethod(boolean needBody) {
            this.needBody = needBody;
        }
    }

    public static final class Md5CalculatedOutputStream extends OutputStream {

        private boolean nocontent = true;

        private final MessageDigest md;
        private final boolean parseEmptyStream;

        public Md5CalculatedOutputStream() throws NoSuchAlgorithmException {
            this(false);
        }

        public Md5CalculatedOutputStream(boolean parseEmptyStream) throws NoSuchAlgorithmException {
            md = MessageDigest.getInstance("md5");
            this.parseEmptyStream = parseEmptyStream;
        }

        @Override public void write(int b) throws IOException {
            if (nocontent) {
                nocontent = false;
            }
            md.update((byte) b);
        }

        @Override public void write(byte b[]) throws IOException {
            if (b == null) {
                throw new NullPointerException();
            } else if (b.length != 0) {
                if (nocontent) {
                    nocontent = false;
                }
                md.update(b);
            }

        }

        @Override public void write(byte b[], int off, int len) throws IOException {
            if (b == null) {
                throw new NullPointerException();
            } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len)
                    < 0)) {
                throw new IndexOutOfBoundsException();
            } else if (len != 0) {
                if (nocontent) {
                    nocontent = false;
                }
                md.update(b, off, len);
            }
        }

        public String toMd5() {
            if (nocontent) {
                return parseEmptyStream ? EMPTY_STRING_MD5 : "";
            }
            return Base64.encodeBase64String(md.digest());
        }
    }
}

c. JS application - Calculate the signature yourself

function sign(url, method, headers, appKey, appSecret, body) {
      const appSecret = appSecret;
      const md5 = function (buffer) {
        return crypto.createHash('md5').update(buffer).digest('base64');
      };
      const sha1 = function (stringToSign, appSecret) {
        return crypto.createHmac('sha1', appSecret).update(stringToSign).digest().toString('base64');
      };
      body = body || {};
      let bodymd5 = '';
      if (body && _.size(body) && ['POST', 'PUT', 'PATCH'].indexOf(method.toUpperCase()) >= 0) {
        bodymd5 = crypto.createHash('md5').update(Buffer.from(JSON.stringify(body))).digest('base64');
      }
      let stringToSign = method + '\n' + Url.parse(url).path + '\n' + headers.date;
      if (bodymd5) {
        stringToSign = stringToSign + '\n' + bodymd5;
      }
      let signature = sha1(stringToSign, appSecret);
      let authHeader = `common-user-ak-v1 ${appKey}:${signature}`;
      return authHeader;
  }