Commit a49daee8 authored by Quxl's avatar Quxl
parents c968de63 fdb6d44c
...@@ -40,7 +40,7 @@ public class AliyunApiController { ...@@ -40,7 +40,7 @@ public class AliyunApiController {
private Messages messages; private Messages messages;
@ResponseBody @ResponseBody
@ApiOperation("获取点播授权STS") @ApiOperation("获取点播授权Auth")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "fileName", dataType = "String", required = true, value = "文件名称(带后缀名)", defaultValue = ""), @ApiImplicitParam(paramType = "query", name = "fileName", dataType = "String", required = true, value = "文件名称(带后缀名)", defaultValue = ""),
@ApiImplicitParam(paramType = "query", name = "title", dataType = "String", required = true, value = "标题", defaultValue = ""), @ApiImplicitParam(paramType = "query", name = "title", dataType = "String", required = true, value = "标题", defaultValue = ""),
......
package com.egolm.film.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.egolm.common.DateUtil;
import com.egolm.common.StringUtil;
import sun.misc.BASE64Encoder;
public class AliyunSign {
private final static Logger LOG = Logger.getLogger(AliyunSign.class.getName());
private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com";
private final static String HTTP_METHOD = "GET";
private final static String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
/**
* 获取CQS 的字符串
*
* @param allParams
* @return
*/
private static String getCQS(List<String> allParams) {
ParamsComparator paramsComparator = new ParamsComparator();
Collections.sort(allParams, paramsComparator);
String cqString = "";
for (int i = 0; i < allParams.size(); i++) {
cqString += allParams.get(i);
if (i != allParams.size() - 1) {
cqString += "&";
}
}
return cqString;
}
private static class ParamsComparator implements Comparator<String> {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
}
/**
* 参数urlEncode
*
* @param value
* @return
*/
private static String percentEncode(String value) {
try {
String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8");
String plusReplaced = urlEncodeOrignStr.replace("+", "%20");
String starReplaced = plusReplaced.replace("*", "%2A");
String waveReplaced = starReplaced.replace("%7E", "~");
return waveReplaced;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
}
private static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) {
List<String> encodeParams = new ArrayList<String>();
if (publicParams != null) {
for (String key : publicParams.keySet()) {
String value = publicParams.get(key);
//将参数和值都urlEncode一下。
String encodeKey = percentEncode(key);
String encodeVal = percentEncode(value);
encodeParams.add(encodeKey + "=" + encodeVal);
}
}
if (privateParams != null) {
for (String key : privateParams.keySet()) {
String value = privateParams.get(key);
//将参数和值都urlEncode一下。
String encodeKey = percentEncode(key);
String encodeVal = percentEncode(value);
encodeParams.add(encodeKey + "=" + encodeVal);
}
}
return encodeParams;
}
private static String hmacSHA1Signature(String accessKeySecret, String stringtoSign) {
try {
String key = accessKeySecret + "&";
try {
SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signKey);
byte[] rawHmac = mac.doFinal(stringtoSign.getBytes());
//按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature)
return new String(new BASE64Encoder().encode(rawHmac));
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
} catch (SignatureException e) {
e.printStackTrace();
}
return "";
}
private static void out(String newLine) {
LOG.log(Level.INFO, newLine);
}
/**
* @param domain 请求地址
* @param httpMethod HTTP请求方式GET,POST等
* @param publicParams 公共参数
* @param privateParams 接口的私有参数
* @return 最后的url
*/
public static String generateURL(String httpMethod,String access_key_secret, Map<String, String> publicParams, Map<String, String> privateParams) {
List<String> allEncodeParams = getAllParams(publicParams, privateParams);
String cqsString = getCQS(allEncodeParams);
out("CanonicalizedQueryString = " + cqsString);
String stringToSign = httpMethod + "&" + percentEncode("/") + "&" + percentEncode(cqsString);
out("StringtoSign = " + stringToSign);
String signature = hmacSHA1Signature(access_key_secret, stringToSign);
out("Signature = " + signature);
return VOD_DOMAIN + "?" + cqsString + "&" + percentEncode("Signature") + "=" + percentEncode(signature);
}
/**
* 生成当前UTC时间戳
*
* @return
*/
public static String generateTimestamp() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
df.setTimeZone(new SimpleTimeZone(0, "GMT"));
return df.format(date);
}
public static void main(String[] args) {
Map<String,String> publicParams = new HashMap<String,String>();
publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", "LTAIOtHCCpDLXYp8");
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp", DateUtil.format(new Date(), DateUtil.FMT_UTC_ALIYUN));
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", StringUtil.getNonceStr());
Map<String,String> privateParams = new HashMap<String,String>();
privateParams.put("Action", "GetMezzanineInfo");
privateParams.put("VideoId", "818e5a5ce8b749d79ee61f3debed95bc");
System.out.println(generateURL( HTTP_METHOD, "LTAIOtHCCpDLXYp8", publicParams, privateParams));
}
}
package com.egolm.film.util; package com.egolm.film.util;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest; import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse; import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest; import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse; import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest; import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse; import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.egolm.common.DateUtil;
import com.egolm.common.HttpsUtil;
import com.egolm.common.StringUtil;
public class AliyunUtil { public class AliyunUtil {
private static String accessKeyId = "";//"LTAIOtHCCpDLXYp8"; private static String accessKeyId = "";//"LTAIOtHCCpDLXYp8";
...@@ -24,6 +33,8 @@ public class AliyunUtil { ...@@ -24,6 +33,8 @@ public class AliyunUtil {
} }
public AliyunUtil(String accessKeyId,String accessKeySecret) { public AliyunUtil(String accessKeyId,String accessKeySecret) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret)); this.aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret));
} }
...@@ -122,4 +133,97 @@ public class AliyunUtil { ...@@ -122,4 +133,97 @@ public class AliyunUtil {
return response; return response;
} }
public void createSts() {
String endpoint = "sts.aliyuncs.com";
String accessKeyId = this.accessKeyId;
String accessKeySecret = this.accessKeySecret;
String roleArn = "acs:ram::1877540435175471:role/siffvodrole";
String roleSessionName = "stsVideo";
String policy = "{\r\n" +
" \"Statement\": [\r\n" +
" {\r\n" +
" \"Action\": \"sts:AssumeRole\",\r\n" +
" \"Effect\": \"Allow\",\r\n" +
" \"Principal\": {\r\n" +
" \"RAM\": [\r\n" +
" \"acs:ram::1877540435175471:root\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
" ],\r\n" +
" \"Version\": \"1\"\r\n" +
"}";
System.out.println(policy);
try {
// 添加endpoint(直接使用STS endpoint,前两个参数留空,无需添加region ID)
DefaultProfile.addEndpoint("", "", "Sts", endpoint);
// 构造default profile(参数留空,无需添加region ID)
IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
// 用profile构造client
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
// request.setPolicy(policy); // Optional
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
}
/**
* https://help.aliyun.com/document_detail/59624.html?spm=a2c4g.11174283.6.678.4e66149buh5G0P
* @Title: getVideoSourceFile
* @Description: 获取视频源文件地址
* @param:
* @return: void
* @throws
*/
public void getVideoSourceFile(String videoId) {
Map<String,String> publicParams = new HashMap<String,String>();
/* publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", this.accessKeyId);
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp", AliyunSign.generateTimestamp());
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", StringUtil.getNonceStr()); */
publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", "111");
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp","2018-11-09T08%3A14%3A30Z");
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", "f4291034-4f94-4dc2-bb67-02bbef57c46b");
Map<String,String> privateParams = new HashMap<String,String>();
/* privateParams.put("Action", "GetMezzanineInfo");
privateParams.put("VideoId", "818e5a5ce8b749d79ee61f3debed95bc");*/
// 视频ID
privateParams.put("VideoId", "5aed81b74ba84920be578cdfe004af4b");
// API名称
privateParams.put("Action", "GetVideoPlayAuth");
String url = AliyunSign.generateURL("GET", this.accessKeyId, publicParams, privateParams);
String result = HttpsUtil.doGet(url);
System.out.println(result);
}
public static void main(String[] args) {
AliyunUtil aliyunUtil = new AliyunUtil("111","9XTHW7P9TTRvCsBHBSclOue2tdWOoa");
//aliyunUtil.createSts();
aliyunUtil.getVideoSourceFile("d4b55faeb1b24fb4a4ee06e994e90b76");
}
} }
...@@ -15,3 +15,7 @@ spring.datasource.min-idle=10 ...@@ -15,3 +15,7 @@ spring.datasource.min-idle=10
aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8 aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8
aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa
###\u914D\u7F6E\u963F\u91CC\u4E91\u89C6\u9891\u70B9\u64AD\u4E0A\u4F20\u6240\u9700\u8981\u7684STS\u5BC6\u94A5
aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8
aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment