天天看點

java 移動端接密碼牌_移動遊戲:使用對象存儲服務建構安全令牌服務

java 移動端接密碼牌

This article was originally published on Alibaba Cloud. Thank you for supporting the partners who make SitePoint possible.

本文最初發表在阿裡雲上 。 感謝您支援使SitePoint成為可能的合作夥伴。

Think you got a better tip for making the best use of Alibaba Cloud services? Tell us about it and go in for your chance to win a Macbook Pro (plus other cool stuff). Find out more here.

認為您有更好的技巧來充分利用阿裡雲服務嗎? 告訴我們,并争取獲得Macbook Pro的機會(還有其他很棒的東西)。 在這裡找到更多 。

In mobile gaming, many applications require developers to segregate player resources. This includes a range of things, from saving files to processing user profile information. Using traditional methods, developers can manage this segregation, but must consider many other problems such as security, scalability, and APIs.

在移動遊戲中,許多應用程式要求開發人員隔離玩家資源。 包括從儲存檔案到處理使用者配置檔案資訊等一系列内容。 使用傳統方法,開發人員可以管理這種隔離,但必須考慮許多其他問題,例如安全性,可伸縮性和API。

As cloud technologies evolve, the need for higher-level usability and features is increasing. With Object Storage Service (OSS), customers can store and manage their objects easily and efficiently. OSS provides real-time image processing service online. Some customers may want additional features such as allowing users to have limited access to a service like OSS, but with the convenience of secure, centralized management.

随着雲技術的發展,對更進階别的可用性和功能的需求正在增加。 借助對象存儲服務( OSS ),客戶可以輕松,高效地存儲和管理其對象。 OSS線上提供實時圖像處理服務。 一些客戶可能需要其他功能,例如允許使用者有限地通路OSS之類的服務,但具有安全,集中管理的便利。

Security Token Service provides short-term access permission management for Alibaba Cloud accounts or RAM users. Through STS, you can issue federated users, who are managed in your local account system, with an access credential that customizes the expiration duration and access permission. Federated users can use the STS temporary access credential to directly call the Alibaba Cloud service API or to log on to the Alibaba Cloud Management Console to access authenticated resources.

安全令牌服務為阿裡雲帳戶或RAM使用者提供短期通路權限管理。 通過STS,您可以向在本地帳戶系統中管理的聯盟使用者頒發通路憑據,該憑據可自定義到期時間和通路許可。 聯合使用者可以使用STS臨時通路憑據直接調用阿裡雲服務API或登入到阿裡雲管理控制台以通路經過身份驗證的資源。

In this scenario, we test the functionality of STS by using OSS.

在這種情況下,我們通過使用OSS測試STS的功能。

先決條件 (Prerequisites)

It requires the ability to adjust Resource Access Management (RAM) settings and Roles. For more information, see Roles.

它需要能夠調整資源通路管理(RAM)設定和角色。 有關更多資訊,請參見角色 。

The sample code is written in Python. While it is not required, a basic understanding of computer programming is an advantage. The sample code provided in this tutorial can serve as a template which can be modified to meet your specific needs. Many people are currently using the raw API so as to manage an environment, or an application. While an SDK is available in many languages, the raw API provides more flexibility.

示例代碼是用Python編寫的。 盡管不是必需的,但對計算機程式設計的基本了解是一個優點。 本教程中提供的示例代碼可以用作模闆,可以對其進行修改以滿足您的特定需求。 目前,許多人正在使用原始API來管理環境或應用程式。 雖然有多種語言的SDK,但原始API提供了更大的靈活性。

建築 (Architecture)

java 移動端接密碼牌_移動遊戲:使用對象存儲服務建構安全令牌服務

In this diagram, a RAM user wants to upload images to a separate folder in an OSS bucket.

在此圖中,RAM使用者想要将圖像上傳到OSS存儲桶中的單獨檔案夾。

The upload process is as follows:

上傳過程如下:

  1. The user assumes a RAM role for Read and Write OSS Access for a specific folder in Alibaba Cloud by calling AssumeRole.

    使用者通過調用AssumeRole承擔阿裡雲中特定檔案夾的讀寫OSS通路的RAM角色。

  2. STS returns a set of temporary security credentials.

    STS傳回一組臨時安全憑證。

  3. The user applies the temporary security credentials to access OSS. The user can then make a read or write call on the object.

    使用者應用臨時安全憑證來通路OSS。 然後,使用者可以對對象進行讀取或寫入調用。

We take OSS as an example here. However, STS can be used to grant temporary access to a wide range of Alibaba Cloud services. In this tutorial, we use fine-grained STS permission to limit access to a specific OSS bucket.

這裡以OSS為例。 但是,可以使用STS授予對各種阿裡雲服務的臨時通路權限。 在本教程中,我們使用細粒度的STS權限來限制對特定OSS存儲桶的通路。

實作 (Implementation)

Three files in the sample code are as follows:

示例代碼中的三個檔案如下:

  • sts.py

    sts.py

    • This is the code for assuming the role and to retrieve essential information such as accessKeyId, accessKeySecret, and securityToken.

      這是用于承擔角色并檢索基本資訊(如accessKeyId,accessKeySecret和securityToken)的代碼。

The available functions are as follows:

可用功能如下:

  • Generate signatures to guarantee request authenticity

    生成簽名以保證請求的真實性

  • Get HTTPS requests

    擷取HTTPS請求

The example code for file “sts.py” is as follows:

檔案“ sts.py”的示例代碼如下:

from base64 import b64encode
from datetime import datetime
from Crypto.Hash import SHA, HMAC
import md5, httplib, urllib, uuid, json
##### CONFIG MANAGEMENT
accessKeyId = "<access_key_id>"
accessKeySecret = "<access_key_secret>"
##### FUNCTION MANAGEMENT
def generateSignature(accessKeySecret, stringToSign):
    hmac = HMAC.new(accessKeySecret, stringToSign, SHA)
    return b64encode(hmac.digest())
def getHttpsRequest(host, verb, path):
    conn = httplib.HTTPSConnection(host)
    conn.request(verb, path)
    return conn.getresponse()
# ###### STS MANAGEMENT
host = "sts.aliyuncs.com"
verb = "GET"
bucketName = "<bucket_name>"
folderName = "1"
policy = '{"Statement": [{"Effect": "Allow","Action": ["oss:*"],"Resource": ["acs:oss:*:*:' + bucketName + '/' + folderName + '","acs:oss:*:*:' + bucketName + '/' + folderName + '/*"]}],"Version": "1"}'
dictionaryParams = {
    "AccessKeyId": accessKeyId,
    "Action": "AssumeRole",
    "DurationSeconds": "3600",
    "Format": "JSON",
    "Policy": policy,
    "RoleArn": "acs:ram::5081099437682835:role/ramtestossreadwrite",
    "RoleSessionName": "<session_name>",
    "SignatureMethod": "HMAC-SHA1",
    "SignatureNonce": str(uuid.uuid1()),
    "SignatureVersion": "1.0",
    "Timestamp": datetime.strftime(datetime.utcnow(), "%Y-%m-%dT%H:%M:%SZ"),
    "Version": "2015-04-01"
}
stringToSign = ""
for key in sorted(dictionaryParams.iterkeys()):
    value = urllib.quote(dictionaryParams[key], safe="")
    if stringToSign != "":
        stringToSign += "&"
    stringToSign += key + "=" + value
stringToSign = verb + "&%2F&" + urllib.quote(stringToSign)
signature = generateSignature(accessKeySecret + "&", stringToSign)
dictionaryParams["Signature"] = signature
params = urllib.urlencode(dictionaryParams)
path = "/?" + params
response = getHttpsRequest(host, verb, path)
if response.status == 200:
    jsonData = json.loads(response.read())
    print "Copy paste the respective information to file ossrest.py\n"
    print "accessKeyId: " + jsonData['Credentials']['AccessKeyId']
    print "accessKeySecret: " + jsonData['Credentials']['AccessKeySecret']
    print "securityToken: " + jsonData['Credentials']['SecurityToken']
           
  • ossrest.py

    ossrest.py

    • This is the code to upload and delete the object.

      這是上載和删除對象的代碼。

The available functions are as follows:

可用功能如下:

  • Generate signatures

    生成簽名

  • Generate headers

    産生标題

  • Make HTTP requests

    發出HTTP請求

  • Upload objects

    上載物件

  • Delete objects

    删除物件

The example code for the file “ossrest.py” is as follows:

檔案“ ossrest.py”的示例代碼如下:

from base64 import b64encode
from datetime import datetime
from Crypto.Hash import SHA, HMAC
import md5, httplib, urllib, uuid
##### MAIN CONFIG (STS)
accessKeyId = "<access_key_id>"
accessKeySecret = "<access_key_secret>"
securityToken = "<security_token>"
##### FUNCTION MANAGEMENT
def generateSignature(accessKeySecret, stringToSign):
    hmac = HMAC.new(accessKeySecret, stringToSign, SHA)
    return b64encode(hmac.digest())
def generateHeaders(verb, canonicalizedResource = "/", canonicalizedOSSHeaders = {}, signature = {}):
    # authorization
    stringToSign = verb + "\n"
    if "content" in signature:
        stringToSign += md5.new(signature["content"]).digest()
    stringToSign += "\n"
    if "content_type" in signature:
        stringToSign += signature["content_type"]
    stringToSign += "\n"
    date = datetime.strftime(datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")
    stringToSign += date + "\n"
    if len(canonicalizedOSSHeaders):
        for index, value in canonicalizedOSSHeaders.items():
            stringToSign += index.lower() + ":" + value + "\n"
    stringToSign += canonicalizedResource
    signature = generateSignature(accessKeySecret, stringToSign)
    # headers
    headers = {"Date": date, "Authorization": "OSS " + accessKeyId + ":" + signature}
    headers.update(canonicalizedOSSHeaders)
    return headers
def sendHttpsRequest(host, verb, headers, path = "/", params = ""):
    conn = httplib.HTTPSConnection(host)
    conn.request(verb, path, params, headers)
    return conn.getresponse()
##### OBJECT MANAGEMENT
canonicalizedOSSHeaders = {"x-oss-acl": "public-read", "x-oss-security-token": securityToken}
bucketName = "<bucket_name>"
host = bucketName + ".oss-ap-southeast-1.aliyuncs.com"
hostMain = "oss-ap-southeast-1.aliyuncs.com"
folderName = "1"
fileName = "<filename>"
### UPLOAD OBJECT
verb = "PUT"
canonicalizedResource = "/" + bucketName + "/" + folderName + "/" + fileName
headers = generateHeaders(verb, canonicalizedResource, canonicalizedOSSHeaders)
response = sendHttpsRequest(host, verb, headers, "/" + folderName + "/" + fileName, open(fileName, "rb"))
print "Successfully uploaded " + fileName + " object to " + bucketName + "/" + folderName + " bucket/folder."
print response.status, response.reason
print response.read()
### DELETE OBJECT
verb = "DELETE"
canonicalizedResource = "/" + bucketName + "/" + folderName + "/" + fileName
headers = generateHeaders(verb, canonicalizedResource, canonicalizedOSSHeaders)
response = sendHttpsRequest(host, verb, headers, "/" + folderName + "/" + fileName)
print "Successfully deleted " + fileName + " object."
print response.status, response.reason
print response.read()
           
  • other_sample.py

    other_sample.py

    • This is the code for other scenarios. These samples may not be directly applicable to STS, but are provided as examples.

      這是其他方案的代碼。 這些樣本可能不直接适用于STS,但僅作為示例提供。

The available functions are as follows:

可用功能如下:

  • Create buckets

    建立桶

  • List buckets

    列出桶

  • Upload objects

    上載物件

  • List objects

    列出對象

  • Delete objects

    删除物件

  • Delete buckets

    删除存儲桶

The example code for the file “other_sample.py” is as follows:

檔案“ other_sample.py”的示例代碼如下:

bucketName = "<bucket_name>"
host = bucketName + ".oss-ap-southeast-1.aliyuncs.com"
fileName = "<file_name>"
### CREATE BUCKET
verb = "PUT"
signature = {}
canonicalizedResource = "/" + bucketName + "/"
headers = generateHeaders(verb, signature, canonicalizedResource, canonicalizedOSSHeaders)
response = sendRequest(host, verb, headers)
print "Successfully created " + bucketName + " bucket."
print response.status, response.reason
print response.read()
### LIST BUCKET
host = "oss-ap-southeast-1.aliyuncs.com"
verb = "GET"
signature = {}
canonicalizedResource = "/"
headers = generateHeaders(verb, signature, canonicalizedResource, canonicalizedOSSHeaders)
response = sendRequest(host, verb, headers)
print "Successfully listed buckets."
print response.status, response.reason
print response.read()
### UPLOAD OBJECT
verb = "PUT"
signature = {}
canonicalizedResource = "/" + bucketName + "/" + fileName
headers = generateHeaders(verb, signature, canonicalizedResource, canonicalizedOSSHeaders)
response = sendRequest(host, verb, headers, "/" + fileName, open(fileName, "rb"))
print "Successfully uploaded " + fileName + " object to " + bucketName + " bucket."
print response.status, response.reason
print response.read()
### LIST OBJECT
verb = "GET"
signature = {}
canonicalizedResource = "/" + bucketName + "/"
headers = generateHeaders(verb, signature, canonicalizedResource, canonicalizedOSSHeaders)
response = sendRequest(host, verb, headers)
print "Successfully listed objects in " + bucketName + " bucket."
print response.status, response.reason
print response.read()
### DELETE OBJECT
verb = "DELETE"
signature = {}
canonicalizedResource = "/" + bucketName + "/" + fileName
headers = generateHeaders(verb, signature, canonicalizedResource, canonicalizedOSSHeaders)
response = sendRequest(host, verb, headers, "/" + fileName)
print "Successfully deleted " + fileName + " object."
print response.status, response.reason
print response.read()
### DELETE BUCKET
verb = "DELETE"
signature = {}
canonicalizedResource = "/" + bucketName + "/"
headers = generateHeaders(verb, signature, canonicalizedResource, canonicalizedOSSHeaders)
response = sendRequest(host, verb, headers)
print "Successfully deleted " + bucketName + " bucket."
print response.status, response.reason
print response.read()
           

The expected responses are as follows:

預期的響應如下:

sts.py

:

sts.py

java 移動端接密碼牌_移動遊戲:使用對象存儲服務建構安全令牌服務

ossrest.py

:

ossrest.py

java 移動端接密碼牌_移動遊戲:使用對象存儲服務建構安全令牌服務

結論 (Conclusion)

This example focuses on OSS, but the STS service can be used to control access to other Alibaba Cloud services as well. The use case we describe in this tutorial is gaming. Other scenarios or services which require short-term access to OSS may include:

此示例着重于OSS ,但STS服務也可用于控制對其他阿裡雲服務的通路。 我們在本教程中描述的用例是遊戲。 需要短期通路OSS的其他方案或服務可能包括:

  • Web applications

    網絡應用

  • Mobile applications

    移動應用

附加資訊 (Additional Information)

  • STS Introduction

    STS介紹

  • Use STS to access OSS

    使用STS通路OSS

翻譯自: https://www.sitepoint.com/mobile-gaming-build-a-security-token-service-with-object-storage-service/

java 移動端接密碼牌