Commit 19a3c1d7 by jscat

nyx: oss getToken

1. 添加上传aliyun oss的功能之一, getToken; 测试,成功
parent 10ebc2a2
package cn.com.fun.nyxkey.api.common;
package cn.com.fun.nyxkey.api.common;
......@@ -22,8 +22,11 @@ public enum ExceptionMsg {
FileEmpty("000400","上传文件为空"),
LimitPictureSize("000401","图片大小必须小于2M"),
LimitPictureType("000402","图片格式必须为'jpg'、'png'、'jpge'、'gif'、'bmp'")
LimitPictureType("000402","图片格式必须为'jpg'、'png'、'jpge'、'gif'、'bmp'"),
OSSTokenNameIsBlack("000501", "cardNumber或tokenName不能为空!"),
OSSServerInternalError("000502", "获取阿里oss token失败,服务器内部错误!")
;
private ExceptionMsg(String code, String msg) {
this.code = code;
this.msg = msg;
......
package cn.com.fun.nyxkey.api.common;
package cn.com.fun.nyxkey.api.common;
......@@ -42,26 +42,6 @@ public class JSONResult {
return new JSONResult(resultCode, resultMsg, totalCount, data);
}
// public static JSONResult ok(Object data) {
// return new JSONResult(data);
// }
//
// public static JSONResult ok() {
// return new JSONResult(null);
// }
public static JSONResult errorresultMsg(ExceptionMsg resultMsg) {
return new JSONResult(resultMsg.getCode(), resultMsg.getMsg(), 0, null);
}
public static JSONResult errorMap(Object data) {
return new JSONResult("501", "error", 0, data);
}
public static JSONResult errorTokenresultMsg(String resultMsg) {
return new JSONResult("502", resultMsg, null, null);
}
public static JSONResult errorException(String resultMsg) {
return new JSONResult("555", resultMsg, 0, null);
}
......@@ -69,10 +49,6 @@ public class JSONResult {
public JSONResult() {
}
// public static LeeJSONResult build(Integer resultCode, String resultMsg) {
// return new LeeJSONResult(resultCode, resultMsg, null);
// }
public JSONResult(String resultCode, String resultMsg, Integer totalCount, Object data) {
this.resultCode = resultCode;
this.resultMsg = resultMsg;
......@@ -94,6 +70,14 @@ public class JSONResult {
this.data = null;
}
//如果有额外的错误信息
public JSONResult(ExceptionMsg exceptionMsg, String errorInfo) {
this.resultCode = exceptionMsg.getCode();
this.resultMsg = exceptionMsg.getMsg() + errorInfo;
this.totalCount = 0;
this.data = null;
}
public JSONResult(ExceptionMsg exceptionMsg, Object data) {
this.resultCode = exceptionMsg.getCode();
this.resultMsg = exceptionMsg.getMsg();
......
package cn.com.fun.nyxkey.api.config;
package cn.com.fun.nyxkey.api.config;
......@@ -39,7 +39,6 @@ public class DataSourceConfig {
private Map<String,Object> loadPropertiesToMap(String path) throws IOException {
String filePath = System.getProperty("user.dir") + "/" + path;
//InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
File file = new File(filePath);
InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
......
package cn.com.fun.nyxkey.api.service;
package cn.com.fun.nyxkey.api.service;
......@@ -14,6 +14,6 @@ import java.util.List;
*/
public interface Rockwell_ossService {
JSONResult Rockwell_ossServiceGetToken();
JSONResult Rockwell_ossServiceGetToken(String userName, String tokenName);
}
package cn.com.fun.nyxkey.api.service.impl;
package cn.com.fun.nyxkey.api.service.impl;
package cn.com.fun.nyxkey.api.service.impl;
import cn.com.fun.nyxkey.api.common.ExceptionMsg;
import cn.com.fun.nyxkey.api.common.JSONResult;
import cn.com.fun.nyxkey.api.common.Pagination;
import cn.com.fun.nyxkey.api.repository.*;
......@@ -7,6 +8,14 @@ import cn.com.fun.nyxkey.api.service.*;
import cn.com.fun.nyxkey.api.domain.*;
import cn.com.fun.nyxkey.api.domain.query.*;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.K;
import org.joda.time.DateTime;
......@@ -16,10 +25,12 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
......@@ -33,11 +44,34 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService {
private static final Logger LOGGER = LoggerFactory.getLogger(Rockwell_ossServiceImpl.class);
@Value("${weixin.appid}")
private String accessKeyId;
//目前只有cn-hangzhou这个region可以用
@Value("${aliyun.oss.REGION_CN_HANGZHOU}")
private String aliyunOssREGION_CN_HANGZHOU;
@Value("${weixin.secret}")
private String accessKeySecret;
//AccessKeyId表示RAM子账号的AccessKeyId;
@Value("${aliyun.oss.AccessKeyID}")
private String aliyunOssAccessKeyID;
//AccessKeySecret表示RAM子账号的AccessKeySecret;
@Value("${aliyun.oss.AccessKeySecret}")
private String aliyunOssAccessKeySecret;
@Value("${aliyun.oss.STS_API_VERSION}")
private String aliyunOssSTS_API_VERSION;
//RoleArn表示的是需要扮演的角色ID,表示某种操作权限的虚拟概念,但是没有独立的登陆密码和AccessKey
@Value("${aliyun.oss.RoleArn}")
private String aliyunOssRoleArn;
//PolicyFile表示的是在扮演角色的时候额外加上的一个权限限制;
//用来定义权限的规则,比如允许用户读取、或者写入某些资源
@Value("${aliyun.oss.PolicyFile}")
private String aliyunOssPolicyFile;
//TokenExpireTime指的是临时凭证的有效期,单位是s,最小为900,最大为3600;
//token时间,默认是30分钟,单位(分钟)
@Value("${aliyun.oss.TokenExpireTime}")
private int aliyunOssTokenExpireTime;
/*
接口api:
......@@ -50,37 +84,108 @@ public class Rockwell_ossServiceImpl implements Rockwell_ossService {
「OSS」阿里云OSS之STS临时访问授权
https://www.jianshu.com/p/a6047c5b3d3d
*/
public JSONResult Rockwell_ossServiceGetToken()
{
String upload_dir = "user-dir/";
int expire_time = 30;
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.SECOND, expire_time); // expire_time = 30
Date expire_syncpoint = c.getTime();
String expire = getISO8601Timestamp(expire_syncpoint);
Map policy_dict = new HashMap();
policy_dict.put("expiration", expire);
public JSONResult Rockwell_ossServiceGetToken(String userName, String tokenName)
{
if (StringUtils.isBlank(userName) || StringUtils.isBlank(tokenName)) {
return new JSONResult(ExceptionMsg.OSSTokenNameIsBlack);
}
try {
// 获取临时授权token
AssumeRoleResponse assumeRoleResponse = assumeRole(tokenName);
// 构造返回参数
Map<String,String> map = new HashMap<String,String>();
// 账号ID
map.put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId());
// 密码
map.put("accessKeySecret", assumeRoleResponse.getCredentials().getAccessKeySecret());
// token
map.put("securityToken", assumeRoleResponse.getCredentials().getSecurityToken());
// 有效时间
map.put("expiration", assumeRoleResponse.getCredentials().getExpiration());
JSONResult json = new JSONResult();
return new JSONResult(1, map);
} catch (ClientException e) {
e.printStackTrace();
return new JSONResult(ExceptionMsg.OSSServerInternalError, " 错误码:"+ e.getErrCode() + ";错误信息:" + e.getErrMsg());
}
}
return json;
public AssumeRoleResponse assumeRole(String roleSessionName) throws ClientException {
// 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
// 只有 RAM用户(子账号)才能调用 AssumeRole 接口
// 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
// 请首先在RAM控制台创建一个RAM用户,并为这个用户创建AccessKeys
IClientProfile profile = DefaultProfile.getProfile(aliyunOssREGION_CN_HANGZHOU, aliyunOssAccessKeyID,
aliyunOssAccessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
// 创建一个 AssumeRoleRequest 并设置请求参数
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setVersion(aliyunOssSTS_API_VERSION);
request.setMethod(MethodType.POST);
// 此处必须为 HTTPS
request.setProtocol(ProtocolType.HTTPS);
// RoleArn 需要在 RAM 控制台上获取
request.setRoleArn(aliyunOssRoleArn);
// RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
// 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
// 具体规则请参考API文档中的格式要求
request.setRoleSessionName(roleSessionName);
// 授权策略
request.setPolicy(readJson(aliyunOssPolicyFile));
// 设置token时间
request.setDurationSeconds(aliyunOssTokenExpireTime * 60L);
// 发起请求,并得到response
return client.getAcsResponse(request);
}
/**
* 传入Data类型日期,返回字符串类型时间(ISO8601标准时间)
* @param date
* @return
*/
public static String getISO8601Timestamp(Date date){
TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(date);
return nowAsISO;
public String readJson(String path) {
String filePath = "/config/" + path;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
// 返回值,使用StringBuffer
StringBuffer data = new StringBuffer();
//
try {
inputStream = new ClassPathResource(filePath).getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
// 每次读取文件的缓存
String temp = null;
while ((temp = reader.readLine()) != null) {
data.append(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭文件流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data.toString();
}
}
package cn.com.fun.nyxkey.api.web.controller;
package cn.com.fun.nyxkey.api.web.controller;
......@@ -11,11 +11,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/*
API接口
用于小程序的相关验证
1. 敏感文本验证
......
package cn.com.fun.nyxkey.api.web.controller;
package cn.com.fun.nyxkey.api.web.controller;
......@@ -16,21 +16,14 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static cn.com.fun.nyxkey.api.utils.BaseUtils.cookieSign;
import static cn.com.fun.nyxkey.api.utils.BaseUtils.getSession;
/**
* Created by jscat on 2020-02-17.
*
* page接口
* 用于www.winenyx.com的页面跳转
*
*
*/
@Controller
@RequestMapping("/")
......
package cn.com.fun.nyxkey.api.web.controller;
package cn.com.fun.nyxkey.api.web.controller;
......@@ -6,11 +6,12 @@ import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/*
page接口
用于index页面跳转
*/
@Controller
@RequestMapping("/")
......
package cn.com.fun.nyxkey.api.web.controller;
package cn.com.fun.nyxkey.api.web.controller;
......@@ -15,11 +15,14 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/*
API接口
用于小程序的评论接口
*/
/**
* Created by jscat on 2020-01-03.
*/
......
package cn.com.fun.nyxkey.api.web.controller;
package cn.com.fun.nyxkey.api.web.controller;
......@@ -16,11 +16,14 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/*
API接口
用于小程序的知识问答接口
*/
/**
* Created by jscat on 2019-11-11.
*/
......
package cn.com.fun.nyxkey.api.web.controller;
package cn.com.fun.nyxkey.api.web.controller;
......@@ -14,13 +14,14 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by jscat on 2020-04-21.
*
* API接口
* 用于小程序的相关验证
* 1. 敏感文本验证
*
*
*/
@RestController
@RequestMapping("/api")
......@@ -32,14 +33,18 @@ public class OssApiController {
private Rockwell_ossService ossService;
// 3.0 oss getToken api
@ApiOperation(value="test", notes="test")
@ApiOperation(value="获取阿里云oss token", notes="获取阿里云oss token")
@ApiImplicitParams({
@ApiImplicitParam(name = "userName", value = "用户名", required = false, dataType = "String", defaultValue = "1"),
@ApiImplicitParam(name = "tokenName", value = "android传入android,ios传入ios", required = false, dataType = "String", defaultValue = "1")
})
@RequestMapping(value = "/nyx/auth/id/getToken", method = RequestMethod.GET)
public void RockwellAliyunOssGetToken(
@RequestMapping(value = "/nyx/oss/getToken", method = RequestMethod.GET)
public JSONResult RockwellAliyunOssGetToken(
@RequestParam(value = "userName", required = false, defaultValue = "1") String userName,
@RequestParam(value = "tokenName", required = false, defaultValue = "ios") String tokenName
) {
ossService.Rockwell_ossServiceGetToken();
return ossService.Rockwell_ossServiceGetToken(userName, tokenName);
}
}
......
package cn.com.fun.nyxkey.api.web.controller;
package cn.com.fun.nyxkey.api.web.controller;
......@@ -19,15 +19,14 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static cn.com.fun.nyxkey.api.utils.BaseUtils.cookieSign;
import static cn.com.fun.nyxkey.api.utils.BaseUtils.getSession;
/**
* Created by jscat on 2020-02-17.
*
* * API接口
* * 用于小程序的用户接口
* * 1. 微信登陆
* * 2. 注册
*/
@RestController
@RequestMapping("/api")
......
server:
server:
......@@ -64,3 +64,13 @@ app:
weixin:
appid: 'wx72555e77d9e5cee2'
secret: '072986d584176aa5aa9b1531841779f2'
aliyun:
oss:
REGION_CN_HANGZHOU: cn-hangzhou
AccessKeyID: LTAI4GA88LJ82UtfMUrozDp3
AccessKeySecret: OWyAIN3OTobk9MuKvZ7DMnr5cJxNND
STS_API_VERSION: 2015-04-01
RoleArn: acs:ram::1956317109339291:role/nyxtokengeneratorrolepolicy
PolicyFile: policy/bucket_full_access_policy.txt
TokenExpireTime: 30
\ No newline at end of file
{
{
"Statement": [
{
"Action": "oss:*",
"Effect": "Allow",
"Resource": [
"acs:oss:*:*:930-test-sh",
"acs:oss:*:*:930-test-sh/*"
]
}
],
"Version": "1"
}
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论