java 移动端接口令牌_移动游戏:使用对象存储服务构建安全令牌服务

本文主要是介绍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)

alt

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

alt

ossrest.py:

ossrest.py

alt

结论 (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 移动端接口令牌

这篇关于java 移动端接口令牌_移动游戏:使用对象存储服务构建安全令牌服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/698918

相关文章

JAVA封装多线程实现的方式及原理

《JAVA封装多线程实现的方式及原理》:本文主要介绍Java中封装多线程的原理和常见方式,通过封装可以简化多线程的使用,提高安全性,并增强代码的可维护性和可扩展性,需要的朋友可以参考下... 目录前言一、封装的目标二、常见的封装方式及原理总结前言在 Java 中,封装多线程的原理主要围绕着将多线程相关的操

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Spring Cloud之注册中心Nacos的使用详解

《SpringCloud之注册中心Nacos的使用详解》本文介绍SpringCloudAlibaba中的Nacos组件,对比了Nacos与Eureka的区别,展示了如何在项目中引入SpringClo... 目录Naacos服务注册/服务发现引⼊Spring Cloud Alibaba依赖引入Naco编程s依

java导出pdf文件的详细实现方法

《java导出pdf文件的详细实现方法》:本文主要介绍java导出pdf文件的详细实现方法,包括制作模板、获取中文字体文件、实现后端服务以及前端发起请求并生成下载链接,需要的朋友可以参考下... 目录使用注意点包含内容1、制作pdf模板2、获取pdf导出中文需要的文件3、实现4、前端发起请求并生成下载链接使

Java springBoot初步使用websocket的代码示例

《JavaspringBoot初步使用websocket的代码示例》:本文主要介绍JavaspringBoot初步使用websocket的相关资料,WebSocket是一种实现实时双向通信的协... 目录一、什么是websocket二、依赖坐标地址1.springBoot父级依赖2.springBoot依赖

如何用java对接微信小程序下单后的发货接口

《如何用java对接微信小程序下单后的发货接口》:本文主要介绍在微信小程序后台实现发货通知的步骤,包括获取Access_token、使用RestTemplate调用发货接口、处理AccessTok... 目录配置参数 调用代码获取Access_token调用发货的接口类注意点总结配置参数 首先需要获取Ac

C语言中的浮点数存储详解

《C语言中的浮点数存储详解》:本文主要介绍C语言中的浮点数存储详解,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、首先明确一个概念2、接下来,讲解C语言中浮点型数存储的规则2.1、可以将上述公式分为两部分来看2.2、问:十进制小数0.5该如何存储?2.3 浮点

Java逻辑运算符之&&、|| 与&、 |的区别及应用

《Java逻辑运算符之&&、||与&、|的区别及应用》:本文主要介绍Java逻辑运算符之&&、||与&、|的区别及应用的相关资料,分别是&&、||与&、|,并探讨了它们在不同应用场景中... 目录前言一、基本概念与运算符介绍二、短路与与非短路与:&& 与 & 的区别1. &&:短路与(AND)2. &:非短

Java的volatile和sychronized底层实现原理解析

《Java的volatile和sychronized底层实现原理解析》文章详细介绍了Java中的synchronized和volatile关键字的底层实现原理,包括字节码层面、JVM层面的实现细节,以... 目录1. 概览2. Synchronized2.1 字节码层面2.2 JVM层面2.2.1 ente

讯飞webapi语音识别接口调用示例代码(python)

《讯飞webapi语音识别接口调用示例代码(python)》:本文主要介绍如何使用Python3调用讯飞WebAPI语音识别接口,重点解决了在处理语音识别结果时判断是否为最后一帧的问题,通过运行代... 目录前言一、环境二、引入库三、代码实例四、运行结果五、总结前言基于python3 讯飞webAPI语音