鉴权登陆

鉴权登陆接口,主要是用于根据用户提供的信息登陆全时云直播系统,并获取系统的统一鉴权标志串:token,(请妥善保存token, 丢失token可能会造成他人在token有效期内使用接口修改数据)如果出现token丢失,请及时调用鉴权接口中的token失效方法,保证数据的安全性。

全时云直播提供的所有开放接口,都需要将token作为参数传递给对应的接口,用于对调用方身份的校验。(虽然全时云直播支持多种token的传递方式,但出于安全考虑,建议用户将token放置在请求头中)

新建token

1. 接口描述

接口名称:

/eventopenapi/token/v2/create

发送方式:

POST

参数格式:

accept: application/json;content-type: application/json

2. 请求参数

Http Headers

参数 类型 必须 说明
AppId String 开发者平台分配的AppId
Nonce String 随机数(随机数,最大长度128个字符)
CurTime String 当前UTC时间戳,从1970年1月1日0点0分0秒开始到现在的毫秒数
CheckSum String 服务器认证需要,16进制字符小写SHA1(AppSecret+Nonce+CurTime)

Http Body

3. 输出参数

参数 类型 说明
timeStamp Long 返回时间(时间戳,单位毫秒)
requestId String 请求ID(在接口异常时, 需提供请求ID)
code Int 返回的状态码
msg String 当返回结果的状态码不为200时,包含的错误信息
data Json 返回数据

data 参数说明

参数 类型 说明
token String 统一鉴权token
userId Long 管理员ID
userName String 管理员名称
expire Int token有效时长(时间戳,单位秒)
createTime Long token创建时间(时间戳,单位毫秒)
productId Long 产品ID
customerCode String 客户编码

4. 示例

Headers:
参照Header参数说明

Body:

{

}

输出示例

{
    "timeStamp": 1639470773358,
    "code": 200,
    "msg": "Successfully to create the token!",
    "data": {
        "productId": 80,
        "createTime": 1639470773241,
        "expire": 86400,
        "customerCode": "153857",
        "userName": "云活动测试账号151",
        "userId": 88408809,
        "token": "5d41c4ac806c6440eb6aa8e071115f2b"
    },
    "requestId": "10.255.0.106_20211214_163252_1639470772926"
}

5. Java代码示例

public class TokenUtil {

    @Value(value="${openapi-url}")
    private String openApiUrl;

    @Value(value="${app.id}")
    private String AppId;

    @Value(value="${app.secret}")
    private String AppSecret;

    @Autowired
    private RestTemplate restTemplate;

    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public String createToken() {
        logger.info("createToken.......");
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(MediaType.valueOf("application/json; charset=UTF-8")));
        requestHeaders.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        Map<String, String> headerParameter = getHeaderParam();
        requestHeaders.add("AppId", headerParameter.get("AppId"));
        requestHeaders.add("Nonce", headerParameter.get("Nonce"));
        requestHeaders.add("CurTime", headerParameter.get("CurTime"));
        requestHeaders.add("CheckSum", headerParameter.get("CheckSum"));

        JSONObject param = new JSONObject();
        HttpEntity<String> request = new HttpEntity<String>(param.toString(), requestHeaders);

        ParameterizedTypeReference<ResultData<Token>> typeRef = new ParameterizedTypeReference<ResultData<Token>>() {};
        ResponseEntity<ResultData<Token>> responseEntity = restTemplate.exchange(openApiUrl+"/token/v2/create", HttpMethod.POST, request, typeRef, new Object[] { });
        ResultData<Token> body = responseEntity.getBody();
        Token token = body.getData();
        logger.info("token = " + token);
        return token.getToken();
    }

    private Map<String, String> getHeaderParam() {
        Map<String, String> headerParam = new HashMap<String, String>();
        String nonce = getStringRandom();
        String curTime = String.valueOf(System.currentTimeMillis());
        String checkSum = getCheckSum(AppSecret, nonce, curTime);
        headerParam.put("AppId", AppId);
        headerParam.put("Nonce", nonce);
        headerParam.put("CurTime", curTime);
        headerParam.put("CheckSum", checkSum);
        return headerParam;
    }

    private String getStringRandom() {
        long length = Math.round(Math.random() * 128);
        if(length == 0) length = 32;
        String val = "";
        Random random = new Random();
        //参数length,表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    private String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("SHA1", appSecret + nonce + curTime);
    }

    private String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String getFormattedText(byte[] bytes){
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >>4) &0x0f]);
            buf.append(HEX_DIGITS[bytes[j] &0x0f]);
        }
        return buf.toString();
    }

}