阿里oss服务端签名直传

注意事项:

        服务名称和回调地址的服务名称保持一致,回调地址要作为签名的部分。

        

        回调验签获取不到参数或者乱码,修改代码如下:

public String GetPostBodyParameter(HttpServletRequest request) {
		try {
			String filename = request.getParameter("filename");
			String size = request.getParameter("size");
			String mimeType = request.getParameter("mimeType");
			String height = request.getParameter("height");
			String width = request.getParameter("width");
			filename = URLEncoder.encode(filename, "UTF-8");
			mimeType = URLEncoder.encode(mimeType, "UTF-8");
			return "filename=" + filename +
					"&size=" + size +
					"&mimeType=" + mimeType +
					"&height=" + height +
					"&width=" + width;
		} catch (Exception e) {
		}
		return "";
	}

完整代码如下:

签名代码:

@Override
	public Map<String, Object> getPolicy() {
		CloudStorageConfig config = sysParamsService.getValueObject(Constant.STORAGE_CONFIG_KEY, CloudStorageConfig.class);
		String host = config.getAliyunDomain();
		String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
		String dir = config.getAliyunPrefix()+dateDir; // 用户上传文件时指定的前缀。
		OSS ossClient = new OSSClientBuilder().build(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(), config.getAliyunAccessKeySecret());
		Map<String, Object> respMap = new LinkedHashMap<>();
		try {
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			// PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = ossClient.calculatePostSignature(postPolicy);


			respMap.put("accessid", config.getAliyunAccessKeyId());
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			respMap.put("dir", dir);
			respMap.put("host", host);
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			// respMap.put("expire", formatISO8601Date(expiration));

			JSONObject jasonCallback = new JSONObject();
			jasonCallback.put("callbackUrl", config.getAliyunCallbackUrl());
			jasonCallback.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
			jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
			String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
			respMap.put("callback", base64CallbackBody);
			respMap.put("code", 0);
			return  respMap;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return respMap;
		} finally {
			ossClient.shutdown();
		}
	}

回调代码:
 

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.BinaryUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Enumeration;

/**
 * description: verifyOSS
 * date: 2023/8/31 10:17
 * @author zhangxf
**/
@SuppressWarnings("deprecation")
@WebServlet(asyncSupported = true, urlPatterns = {"/verifyOSS"})
public class CallbackServer extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = 5522372203700422672L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("用户输入url:" + request.getRequestURI());
		response(request, response, "input get ", 200);

	}

	@SuppressWarnings({ "finally" })
	public String executeGet(String url) {
		BufferedReader in = null;

		String content = null;
		try {
			// 定义HttpClient
			@SuppressWarnings("resource")
			DefaultHttpClient client = new DefaultHttpClient();
			// 实例化HTTP方法
			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);

			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			content = sb.toString();
		} catch (Exception e) {
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return content;
		}
	}

	public String GetPostBody(InputStream is, int contentLen) {
		if (contentLen > 0) {
			int readLen = 0;
			int readLengthThisTime = 0;
			byte[] message = new byte[contentLen];
			try {
				while (readLen != contentLen) {
					readLengthThisTime = is.read(message, readLen, contentLen - readLen);
					if (readLengthThisTime == -1) {// Should not happen.
						break;
					}
					readLen += readLengthThisTime;
				}
				System.out.println("str:"+new String(message));
				return new String(message);
			} catch (IOException e) {
			}
		}
		return "";
	}

	public String GetPostBodyParameter(HttpServletRequest request) {
		try {
			String filename = request.getParameter("filename");
			String size = request.getParameter("size");
			String mimeType = request.getParameter("mimeType");
			String height = request.getParameter("height");
			String width = request.getParameter("width");
			filename = URLEncoder.encode(filename, "UTF-8");
			mimeType = URLEncoder.encode(mimeType, "UTF-8");
			return "filename=" + filename +
					"&size=" + size +
					"&mimeType=" + mimeType +
					"&height=" + height +
					"&width=" + width;
		} catch (Exception e) {
		}
		return "";
	}


	protected boolean VerifyOSSCallbackRequest(HttpServletRequest request, String ossCallbackBody) throws NumberFormatException, IOException
	{
		boolean ret = false;

		Enumeration<String> headers = request.getHeaderNames();
		while (headers.hasMoreElements()) {
			String headerName = headers.nextElement();
			System.out.println("header "+headerName+" "+request.getHeader(headerName));
		}
		String autorizationInput = new String(request.getHeader("Authorization"));
		String pubKeyInput = request.getHeader("x-oss-pub-key-url");
		byte[] authorization = BinaryUtil.fromBase64String(autorizationInput);
		byte[] pubKey = BinaryUtil.fromBase64String(pubKeyInput);
		String pubKeyAddr = new String(pubKey);
		System.out.println("verify pubKeyAddr result:" + pubKeyAddr+":::"+ autorizationInput+"::");

		if (!pubKeyAddr.startsWith("http://gosspublic.alicdn.com/") && !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/"))
		{
			System.out.println("pub key addr must be oss addrss");
			return false;
		}
		String retString = executeGet(pubKeyAddr);
		retString = retString.replace("-----BEGIN PUBLIC KEY-----", "");
		retString = retString.replace("-----END PUBLIC KEY-----", "");
		String queryString = request.getQueryString();
		String uri = request.getRequestURI();
		String decodeUri = java.net.URLDecoder.decode(uri, "UTF-8");
		String authStr = decodeUri;
		if (queryString != null && !queryString.equals("")) {
			authStr += "?" + queryString;
		}
		authStr += "\n" + ossCallbackBody;
		System.out.println("verify authstr result:" + authStr+":::"+ retString+"::"+new String(authorization));

		ret = doCheck(authStr, authorization, retString);
		return ret;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//String ossCallbackBody = GetPostBody(request.getInputStream(), Integer.parseInt(request.getHeader("content-length")));
		//if(StringUtils.isBlank(ossCallbackBody)){
		String ossCallbackBody = GetPostBodyParameter(request);
		System.out.println("OSS Callback Body111:" + ossCallbackBody);
		//}

		boolean ret = VerifyOSSCallbackRequest(request, ossCallbackBody);
		System.out.println("verify result:" + ret);
		System.out.println("OSS Callback Body:" + ossCallbackBody);
		if (ret) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status","ok");
			jsonObject.put("code",0);
			jsonObject.put("data",ossCallbackBody);
			response(request, response, jsonObject.toJSONString(), HttpServletResponse.SC_OK);
		} else {
			response(request, response, "{\"Status\":\"verdify not ok\"}", HttpServletResponse.SC_BAD_REQUEST);
		}
	}

	public static boolean doCheck(String content, byte[] sign, String publicKey) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			byte[] encodedKey = BinaryUtil.fromBase64String(publicKey);
			PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
			java.security.Signature signature = java.security.Signature.getInstance("MD5withRSA");
			signature.initVerify(pubKey);
			signature.update(content.getBytes());
			boolean bverify = signature.verify(sign);
			return bverify;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	private void response(HttpServletRequest request, HttpServletResponse response, String results, int status) throws IOException {
		String callbackFunName = request.getParameter("callback");
		response.addHeader("Content-Length", String.valueOf(results.length()));
		if (callbackFunName == null || callbackFunName.equalsIgnoreCase(""))
			response.getWriter().println(results);
		else
			response.getWriter().println(callbackFunName + "( " + results + " )");
		response.setStatus(status);
		response.flushBuffer();
	}
}

阿里OSS视频直传是一种将视频文件直接上传到阿里OSS的方法。根据提供的引用内容,有两个主要步骤可以帮助您实现阿里OSS视频直传。 第一步是创建签名。根据引用中提供的链接,可以找到阿里云官方文档中关于JavaScript客户端签名直传的详细说明。这个方法适用于通过JavaScript直接与阿里服务器进行交互。您可以按照文档中的指导,使用JavaScript生成签名并将其与视频文件一起发送到阿里OSS。 第二步是在Vue页面中使用视频直传功能。根据引用中提供的代码片段,您可以在Vue页面中使用el-upload组件来实现视频的上传功能。通过设置合适的属性和事件处理程序,您可以将视频文件直接上传到阿里OSS,并获取上传后的视频URL。 请注意,以上仅是提供了一种实现阿里OSS视频直传的方法。根据您的具体需求和情况,可能还需要进行其他设置和逻辑处理。如果您遇到任何问题或需要更多帮助,请参考阿里云官方文档或咨询阿里云技术支持。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [vue element-ui的直传视频到阿里oss(亲测有效)](https://blog.csdn.net/qq_38997036/article/details/107591742)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [阿里oss视频上传及预览图汇总](https://blog.csdn.net/weixin_43816501/article/details/122264881)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值