详情页标题前

阿里云对象存储OSS.NET-云淘科技

详情页1

本文以.NET语言为例,介绍如何在服务端完成签名,并设置上传回调,然后通过表单直传数据到OSS。

前提条件

  • 应用服务器对应的域名可通过公网访问。
  • 应用服务器已安装Visual Studio 2012或更高版本。
  • 应用服务器已经安装.Net Framework 4.5及以上版本。

步骤1:配置应用服务器

  1. 下载应用服务器源码(.NET版本)。
  2. 本示例中以Windows环境为例,将下载的文件解压到C:\callback-server-dotnet目录下。
  3. 进入该目录,找到并打开源码文件TinyHttpServer.cs,修改如下的代码片段:
    // 请填写您的AccessKeyId。
    public static string accessKeyId = "";
    // 请填写您的AccessKeySecret。
    public static string accessKeySecret = "";
    // host的格式为https://bucketname.endpoint,请替换为您的真实信息。
    public static string host = "https://bucketname.oss-cn-hangzhou.aliyuncs.com";
    // callbackUrl为上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
    public static string callbackUrl = "http://192.168.0.1:8888";
    // 用户上传文件时指定的前缀。
    public static string uploadDir = "user-dir-prefix/";
    • accessKeyId:设置您的AccessKeyId。
    • accessKeySecret:设置您的AessKeySecret。
    • host:格式为https://bucketname.endpoint,例如https://bucket-name.oss-cn-hangzhou.aliyuncs.com。关于Endpoint的介绍,请参见Endpoint访问域名。
    • callbackUrl:设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。本例中修改为:String callbackUrl ="http://10.10.10.10:1234";
    • uploadDir:设置上传到OSS文件的前缀,以便于区分文件。您也可以填写空值。
  4. 使用Visual Studio打开aliyun-oss-net-callback-server.sln工程文件,单击启动,生成执行程序aliyun-oss-net-callback-server.exe。

步骤2:配置客户端

  1. 下载客户端源码。
  2. 将文件解压,本例中以解压到D:\aliyun\aliyun-oss-appserver-js目录为例。
  3. 进入该目录,打开upload.js文件,找到下面的代码语句:
    // serverUrl是用户获取签名和Policy等信息的应用服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
    serverUrl = 'http://192.168.0.1:8888'
  4. severUrl改成应用服务器的地址,客户端可以通过它获取签名直传Policy等信息。例如本示例中可修改为:serverUrl = 'http://10.10.10.10:1234'

步骤3:修改CORS

客户端进行表单直传到OSS时,会从浏览器向OSS发送带有Origin的请求消息。OSS对带有Origin头的请求消息会进行跨域规则(CORS)的验证。因此需要为Bucket设置跨域规则以支持Post方法。

  1. 登录OSS管理控制台。
  2. 单击Bucket列表,然后单击目标Bucket名称。
  3. 在左侧导航栏,选择数据安全 > 跨域设置。
  4. 单击创建规则,配置如下图所示。阿里云对象存储OSS.NET-云淘科技

    说明 为了您的数据安全,实际使用时,
    来源建议填写实际允许访问的域名。更多配置信息请参见
    设置跨域访问。

步骤4:体验上传回调

  1. 启动应用服务器。

    在应用服务器的命令行窗口下,进入到
    aliyun-oss-net-callback-server.exe执行程序生成的目录下,执行命令
    aliyun-oss-net-callback-server.exe ${ip} ${port}启动应用服务器。

    cd C:\Users\Desktop\callback-server-dotnet\aliyun-oss-net-callback-server\bin\Debug\  
    aliyun-oss-net-callback-server.exe 10.10.10.10 1234

    说明

    • 程序目录以实际环境为准。您在使用Visual Studio生成aliyun-oss-net-callback-server.exe程序时,可以看到程序目录。
    • ${ip}和${port} 修改成配置应用服务器的IP和端口。例如本示例中为aliyun-oss-net-callback-server.exe 10.10.10.10 1234。
  2. 启动客户端。
    1. 在PC端的客户端源码目录中,打开index.html文件。阿里云对象存储OSS.NET-云淘科技

      重要 index.html文件不保证兼容IE 10以下版本浏览器,若使用IE 10以下版本浏览器出现问题时,您需要自行调试。

    2. 单击选择文件,选择指定类型的文件,单击开始上传。

      上传成功后,显示回调服务器返回的内容。
      阿里云对象存储OSS.NET-云淘科技

应用服务器核心代码解析

应用服务器源码包含了签名直传服务和上传回调服务两个功能。

  • 签名直传服务响应客户端发送给应用服务器的GET消息,代码片段如下:
    private static string GetPolicyToken()
    {
      //expireTime
      var expireDateTime = DateTime.Now.AddSeconds(expireTime);
    
      // example of policy
      //{
      //  "expiration": "2020-05-01T12:00:00.000Z",
      //  "conditions": [
      //    ["content-length-range", 0, 1048576000]
      //    ["starts-with", "$key", "user-dir-prefix/"]
      //  ]
      //}
    
      //policy
      var config = new PolicyConfig();
      config.expiration = FormatIso8601Date(expireDateTime);
      config.conditions = new List<List>();
      config.conditions.Add(new List());
      config.conditions[0].Add("content-length-range");
      config.conditions[0].Add(0);
      config.conditions[0].Add(1048576000);
      config.conditions.Add(new List());
      config.conditions[1].Add("starts-with");
      config.conditions[1].Add("$key");
      config.conditions[1].Add(uploadDir);
    
      var policy = JsonConvert.SerializeObject(config);
      var policy_base64 = EncodeBase64("utf-8", policy);
      var signature = ComputeSignature(accessKeySecret, policy_base64);
    
      //callback
      var callback = new CallbackParam();
      callback.callbackUrl = callbackUrl;
      callback.callbackBody = "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}";
      callback.callbackBodyType = "application/x-www-form-urlencoded";
    
      var callback_string = JsonConvert.SerializeObject(callback);
      var callback_string_base64 = EncodeBase64("utf-8", callback_string);
    
      var policyToken = new PolicyToken();
    
      policyToken.accessid = accessKeyId;
      policyToken.host = host;
      policyToken.policy = policy_base64;
      policyToken.signature = signature;
      policyToken.expire = ToUnixTime(expireDateTime);
      policyToken.callback = callback_string_base64;
      policyToken.dir = uploadDir;
    
      return JsonConvert.SerializeObject(policyToken);
    }
    
    public void DoGet()
    {
      Console.WriteLine("DoGet request: {0}", this.httpURL);
      var content = GetPolicyToken();
      this.swResponse.WriteLine("HTTP/1.0 200 OK");
      this.swResponse.WriteLine("Content-Type: application/json"); 
      this.swResponse.WriteLine("Access-Control-Allow-Origin: *");
      this.swResponse.WriteLine("Access-Control-Allow-Method: GET, POST");
      this.swResponse.WriteLine($"Content-Length: {content.Length.ToString()}");
      this.swResponse.WriteLine("Connection: close");
      this.swResponse.WriteLine("");
      this.swResponse.WriteLine(content);
    }
    
    
  • 上传回调服务响应OSS发送给应用服务器的POST消息,代码片段如下:
    public bool VerifySignature()
    {
      // Get the Authorization Base64 from Request
      if (this.httpHeadersDict["authorization"] != null)
      {
        this.strAuthorizationRequestBase64 = this.httpHeadersDict["authorization"].ToString();
      } else if (this.httpHeadersDict["Authorization"] != null) {
        this.strAuthorizationRequestBase64 = this.httpHeadersDict["Authorization"].ToString();
      }
      if (this.strAuthorizationRequestBase64 == "")
      {
        Console.WriteLine("authorization property in the http request header is null. ");
        return false;
      }
    
      // Decode the Authorization from Request
      this.byteAuthorizationRequest = Convert.FromBase64String(this.strAuthorizationRequestBase64);
    
      // Decode the URL of PublicKey
      this.strPublicKeyURLBase64 = this.httpHeadersDict["x-oss-pub-key-url"].ToString();
      var bytePublicKeyURL = Convert.FromBase64String(this.strPublicKeyURLBase64);
      var strAsciiPublickeyURL = System.Text.Encoding.ASCII.GetString(bytePublicKeyURL);
    
      // Get PublicKey from the URL
      ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(validateServerCertificate);
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strAsciiPublickeyURL);
      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
      StreamReader srPublicKey = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
      this.strPublicKeyBase64 = srPublicKey.ReadToEnd();
      response.Close();
      srPublicKey.Close();
      this.strPublicKeyContentBase64 = this.strPublicKeyBase64.Replace("-----BEGIN PUBLIC KEY-----
    ", "").Replace("-----END PUBLIC KEY-----", "").Replace("
    ", "");
      this.strPublicKeyContentXML = this.RSAPublicKeyString2XML(this.strPublicKeyContentBase64);
    
      // Generate the New Authorization String according to the HttpRequest
      String[] arrURL;
      if (this.httpURL.Contains('?'))
      {
        arrURL = this.httpURL.Split('?');
        this.strAuthSourceForMD5 = String.Format("{0}?{1}
    {2}", System.Web.HttpUtility.UrlDecode(arrURL[0]), arrURL[1], this.httpBody);
      }
      else
      {
        this.strAuthSourceForMD5 = String.Format("{0}
    {1}", System.Web.HttpUtility.UrlDecode(this.httpURL), this.httpBody);
      }
    
      // MD5 hash bytes from the New Authorization String 
      var byteAuthMD5 = byteMD5Encrypt32(this.strAuthSourceForMD5);
    
      // Verify Signature
      System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
      try
      {
        RSA.FromXmlString(this.strPublicKeyContentXML);
      }
      catch (System.ArgumentNullException e)
      {
        throw new ArgumentNullException(String.Format("VerifySignature Failed : RSADeformatter.VerifySignature get null argument : {0} .", e));
      }
      catch (System.Security.Cryptography.CryptographicException e)
      {
        throw new System.Security.Cryptography.CryptographicException(String.Format("VerifySignature Failed : RSA.FromXmlString Exception : {0} .", e));
      }
      System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
      RSADeformatter.SetHashAlgorithm("MD5");
    
      var bVerifyResult = false;
      try
      {
        bVerifyResult = RSADeformatter.VerifySignature(byteAuthMD5, this.byteAuthorizationRequest);
      }
      catch (System.ArgumentNullException e)
      {
        throw new ArgumentNullException(String.Format("VerifySignature Failed : RSADeformatter.VerifySignature get null argument : {0} .", e));
      }
      catch (System.Security.Cryptography.CryptographicUnexpectedOperationException e)
      {
        throw new System.Security.Cryptography.CryptographicUnexpectedOperationException(String.Format("VerifySignature Failed : RSADeformatter.VerifySignature Exception : {0} .", e));
      }
    
      return bVerifyResult;
    }
    
    public void DoPost()
    {
      this.GetPostBody();
    
      // Verify Signature
      try
      {
        if (this.VerifySignature())
        {
          Console.WriteLine("
    VerifySignature Successful . 
    ");
    
          // do something accoding to callback_body ... 
    
          this.HttpResponseSuccess();
        }
        else
        {
          Console.WriteLine("
    VerifySignature Failed . 
    ");
          this.HttpResponseFailure();
        }
      }
      catch
      {
        Console.WriteLine("
    VerifySignature Failed . 
    ");
        this.HttpResponseFailure();
      }
    }
  • 内容没看懂? 不太想学习?想快速解决? 有偿解决: 联系专家

    阿里云企业补贴进行中: 马上申请

    腾讯云限时活动1折起,即将结束: 马上收藏

    同尘科技为腾讯云授权服务中心。

    购买腾讯云产品享受折上折,更有现金返利:同意关联,立享优惠

    转转请注明出处:https://www.yunxiaoer.com/158678.html

    (0)
    上一篇 2023年12月10日
    下一篇 2023年12月10日
    详情页2

    相关推荐

    • 阿里云负载均衡API概览-云淘科技

      本产品(负载均衡/2014-05-15)的OpenAPI采用RPC签名风格,签名细节参见签名机制说明。我们已经为开发者封装了常见编程语言的SDK,开发者可通过下载SDK直接调用本产品OpenAPI而无需关心技术细节。如果现有SDK不能满足使用需求,可通过签名机制进行自签名对接。由于自签名细节非常复杂,需花费 5个工作日左右。因此建议加入我们的服务钉钉群(11…

      阿里云负载均衡 2023年12月10日
    • 阿里云人工智能平台PAICreateService – 创建服务-云淘科技

      创建PAI-EAS服务。 接口说明 请确保在使用该接口前,已充分了解EAS产品的收费方式和价格。 调试 您可以在OpenAPI Explorer中直接运行该接口,免去您计算签名的困扰。运行成功后,OpenAPI Explorer可以自动生成SDK代码示例。 调试调试授权信息下表是API对应的授权信息,可以在RAM权限策略语句的Action元素中使用,用来给R…

      2023年12月10日
    • 阿里云对象存储OSS计费案例-云淘科技

      本文以案例形式介绍对象存储OSS费用的计算方法。 注意事项 以下案例单价来自2018年1月3日阿里云官网公布的详细价格信息。单价的变动请以阿里云官网发布的数据为准。 OSS产品定价中明确了存储费用的单价为元/GB/月,但按量计费的计算方法为实际资源使用量×每小时单价。因此当您需要计算实际存储费用时,需要先将存储费用的单价转换为元/GB/小时。按小时结算的单价…

      阿里云对象存储 2023年12月10日
    • 信息流广告,信息流部分建议宽度830px,只针对默认列表样式,顺序随机
    • 阿里云对象存储OSSJava存储空间清单-云淘科技

      本文介绍如何添加、查看、批量列举和删除存储空间(Bucket)的清单(Inventory)配置。 注意事项 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见访问域名和数据中心。 本文以从环境变量读取访问凭证为例。如…

      阿里云对象存储 2023年12月10日
    • 阿里云对象存储OSSJava列举文件-云淘科技

      本文介绍如何列举指定存储空间下(Bucket)的所有文件(Object)、指定个数的文件、指定前缀的文件等。 注意事项 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见访问域名和数据中心。 本文以从环境变量读取访问…

      阿里云对象存储 2023年12月10日

    联系我们

    400-800-8888

    在线咨询: QQ交谈

    邮件:admin@example.com

    工作时间:周一至周五,9:30-18:30,节假日休息

    关注微信
    本站为广大会员提供阿里云、腾讯云、华为云、百度云等一线大厂的购买,续费优惠,保证底价,买贵退差。