“浙里办”统一用户组件-接入 基于单点登录票据换取请求 token

基于单点登录票据换取请求 token

1. 请求地址

政务外网地址:
https://bcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220329000007/
uc/sso/access_token
互联网地址:
https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220329000007
/uc/sso/access_token

2. 入参

3. 出参

直接上代码
package com.central.utils;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
public class HmacAuthUtil {

    public static void main(String[] args) {
        String urlStr = "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220329000007\n" +
                "/uc/sso/access_token";
        String requestMethod = "POST";
        String accessKey = "你的accessKey ";
        String secretKey = "你的secretKey ";

        Map<String, String> headers = generateHeader(urlStr, requestMethod, accessKey, secretKey);

        // 使用headers来发起HTTP请求
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("ticketId", "你的ticketId");
        parameters.put("appId", "你的appId");
        // 发起请求
        HttpResponse response = HttpRequest.post(urlStr)
                .headerMap(headers, true) // 设置请求头
                .body(JSON.toJSONString(parameters), "application/json") // 设置表单参数
                .execute();

        // 打印响应状态码
        System.out.println("Status Code: " + response.getStatus());
        String body = response.body();
        // 打印响应体
        System.out.println("Response Body: " + body);
        JSONObject jo = JSONObject.parseObject(body);
        JSONObject data = jo.getJSONObject("data");
        System.err.println("data:" + data);
    }


    /**
     * 构造请求 header * @param urlStr 请求 url,全路径格式,比如:
     * https://bcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220905000004/uc/auth/verify/sendMessage * @param requestMethod 请求方法,大写格式,如:GET, POST * @param accessKey 应用的 AK
     *
     * @param secretKey 应用的 SK
     * @return
     */
    public static Map<String, String> generateHeader(String urlStr, String requestMethod, String accessKey, String secretKey) {
        log.info("params,urlStr={},requestMethod={},accessKey={},secretKey={}", urlStr, requestMethod, accessKey, secretKey);
        Map<String, String> header = new HashMap<>();
        try {
            DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = dateFormat.format(new Date());
            URL url = new URL(urlStr);
            URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
            String canonicalQueryString = getCanonicalQueryString(uri.getQuery());
            String message = requestMethod.toUpperCase() + "\n" + uri.getPath() + "\n" +
                    canonicalQueryString + "\n" + accessKey + "\n" + date + "\n";
            Mac hasher = Mac.getInstance("HmacSHA256");
            hasher.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"));
            byte[] hash = hasher.doFinal(message.getBytes());
            // to lowercase hexits
            DatatypeConverter.printHexBinary(hash);
            // to base64
            String sign = DatatypeConverter.printBase64Binary(hash);
            header.put("X-BG-HMAC-SIGNATURE", sign);
            header.put("X-BG-HMAC-ALGORITHM", "hmac-sha256");
            header.put("X-BG-HMAC-ACCESS-KEY", accessKey);
            header.put("X-BG-DATE-TIME", date);
        } catch (Exception e) {
            log.error("generate error", e);
            throw new RuntimeException("generate header error");
        }
        log.info("header info,{}", header);
        return header;
    }

    private static String getCanonicalQueryString(String query) {
        if (query == null || query.trim().length() == 0) {
            return "";
        }
        List<Pair<String, String>> queryParamList = new ArrayList<>();
        String[] params = query.split("&");
        for (String param : params) {
            int eqIndex = param.indexOf("=");
            String key = param.substring(0, eqIndex);
            String value = param.substring(eqIndex + 1);
            Pair<String, String> pair = new Pair<String, String>(key, value);
            queryParamList.add(pair);
        }
        List<Pair<String, String>> sortedParamList = queryParamList.stream().sorted(Comparator.comparing(param -> param.getKey() + "=" +
                Optional.ofNullable(param.getValue()).orElse(""))).collect(Collectors.toList());
        List<Pair<String, String>> encodeParamList = new ArrayList<>();
        sortedParamList.stream().

                forEach(param ->

                {
                    try {
                        String key = URLEncoder.encode(param.getKey(), "utf-8");
                        String value = URLEncoder.encode(Optional.ofNullable(param.getValue()).orElse(""), "utf-8")
                                .replaceAll("\\%2B", "%20")
                                .replaceAll("\\+", "%20")
                                .replaceAll("\\%21", "!")
                                .replaceAll("\\%27", "'")
                                .replaceAll("\\%28", "(")
                                .replaceAll("\\%29", ")")
                                .replaceAll("\\%7E", "~")
                                .replaceAll("\\%25", "%");
                        encodeParamList.add(new Pair<>(key, value));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException("encoding error");
                    }
                });
        StringBuilder queryParamString = new StringBuilder(64);
        for (Pair<String, String> encodeParam : encodeParamList) {
            queryParamString.append(encodeParam.getKey()).append("=").append(Optional.ofNullable(encodeParam.getValue()).orElse(""));
            queryParamString.append("&");
        }
        return queryParamString.substring(0, queryParamString.length() - 1);
    }

}

4 . 返回结果

{
    "data": {
        "accessToken": "debug_at_6666666666666666666666666666"
    },
    "resp_code": 0,
    "resp_msg": "",
    "success": true,
    "showType": 4,
    "traceId": "traceId111",
    "host": "host2222",
    "total": "0"
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值