com.aliyun.sdk.gateway.eiam.dev.auth.RoaSignatureComposer Maven / Gradle / Ivy
The newest version!
package com.aliyun.sdk.gateway.eiam.dev.auth;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.utils.StringUtils;
import java.util.*;
public class RoaSignatureComposer {
private final static String SEPARATOR = "&";
private final static String ACCEPT = "accept";
private final static String CONTENT_MD5 = "content-md5";
private final static String CONTENT_TYPE = "content-type";
private final static String DATE = "date";
private final static String prefix = "x-acs-";
public static String composeStringToSign(HttpMethod method, Map params,
Map headers, String pathname) {
String accept = headers.get(ACCEPT) == null ? StringUtils.EMPTY : headers.get(ACCEPT);
String contentMD5 = headers.get(CONTENT_MD5) == null ? StringUtils.EMPTY : headers.get(CONTENT_MD5);
String contentType = headers.get(CONTENT_TYPE) == null ? StringUtils.EMPTY : headers.get(CONTENT_TYPE);
String date = headers.get(DATE) == null ? StringUtils.EMPTY : headers.get(DATE);
String header = method + "\n" + accept + "\n" + contentMD5 + "\n" + contentType + "\n" + date + "\n";
String canonicalizedHeaders = buildCanonicalizedHeaders(headers);
String canonicalizedResource = buildCanonicalizedResource(pathname, params);
return header + canonicalizedHeaders + canonicalizedResource;
}
private static String buildCanonicalizedHeaders(Map headers) {
Set keys = headers.keySet();
List canonicalizedKeys = new ArrayList<>();
for (String key : keys) {
if (key.startsWith(prefix)) {
canonicalizedKeys.add(key);
}
}
Collections.sort(canonicalizedKeys);
StringBuilder canonicalizedHeaders = new StringBuilder();
for (String key : canonicalizedKeys) {
canonicalizedHeaders.append(key);
canonicalizedHeaders.append(":");
canonicalizedHeaders.append(headers.get(key).trim());
canonicalizedHeaders.append("\n");
}
return canonicalizedHeaders.toString();
}
private static String buildCanonicalizedResource(String pathname, Map params) {
if (params.size() <= 0) {
return pathname;
}
String[] keys = params.keySet().toArray(new String[params.size()]);
StringBuilder queryString = new StringBuilder(pathname);
queryString.append("?");
Arrays.sort(keys);
for (int i = 0; i < keys.length; i++) {
queryString.append(keys[i]);
if (!StringUtils.isEmpty(params.get(keys[i]))) {
queryString.append("=");
queryString.append(params.get(keys[i]));
}
queryString.append(SEPARATOR);
}
return queryString.length() > 0 ? queryString.deleteCharAt(queryString.length() - 1).toString() : StringUtils.EMPTY;
}
}