Cosmos db Rest API - 错误 401 未经授权 [英] Cosmos db Rest API - Error 401 Unauthorized

查看:101
本文介绍了Cosmos db Rest API - 错误 401 未经授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 REST API 向使用 android 的 db cosmos 获取 get 请求!azure cosmos db 有一个特定的标题,但我认为一切都是正确的

I'm trying to get a get request to the db cosmos using android, using REST API! The azure cosmos db has a specific heading, but I think everything is correct

但是,当我使用 Http REST API 时,我收到错误 Unauthorized 401,你能帮我吗?

However, when I use Http REST API I get the error Unauthorized 401, can you help me?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    n = findViewById(R.id.teste11);
    Button buttonParse = findViewById(R.id.button_parse);
    buttonParse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                getwebservice();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    client = new OkHttpClient();


}

Getwebservices 方法

Getwebservices method

 private void getwebservice() throws Exception {

    String headerDate = getDateString();

    String gen = generateAuthHeader("GET", "docs", "dbs/tempdb/colls/tempcoll/docs/WakefieldFamily",
            headerDate, PRIMARY_KEY);
    final Request request = new Request.Builder()
            .url("https://***.documents.azure.com:443/dbs/***/colls/***/docs/WakefieldFamily")
            .get()
            .addHeader("Accept", "application/json")
            .addHeader("x-ms-version", "2017-02-22")
            .addHeader("Authorization", gen)
            .addHeader("x-ms-date", headerDate)
            .addHeader("cache-control", "no-cache")
            .build();

    okhttp3.Response response = null;
    client.newCall(request).enqueue(new Callback() {
        Headers g = request.headers();
        @Override
        public void onFailure(okhttp3.Call call, IOException e) {
             MainActivity.this.runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     String g = "oi";

                 }
             });
        }

        @Override
        public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    n.setText(String.valueOf(response.code()));
                }
            });
        }
    });

    }

这些是签名和标题日期的辅助方法

These are the auxiliary methods for signature and header date

 public String getDateString() {
    SimpleDateFormat formatter =
            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    return formatter.format(new Date()).toLowerCase();

}

public String generateAuthHeader(String verb, String resourceType, String resourceId, String date, String masterKeyBase64) throws Exception {

    byte[] masterKeyBytes = Base64.decode(masterKeyBase64, Base64.NO_WRAP);
    Mac mac = Mac.getInstance("HMACSHA256");
    mac.init(new SecretKeySpec(masterKeyBytes, "HMACSHA256"));

    //Build the unsigned auth string.
    String stringToSign = verb.toLowerCase() + "\n"
            + resourceType.toLowerCase() + "\n"
            + resourceId + "\n"
            + date.toLowerCase() + "\n"
            + "\n";

    //Sign and encode the auth string.
    String signature = Base64.encodeToString(mac.doFinal(stringToSign.toLowerCase().getBytes("UTF-8")), Base64.NO_WRAP);

    //Generate the auth header.
    String authHeader = URLEncoder.encode("type=master&ver=1.0&sig=" + signature, "UTF-8");

    return authHeader;
}

我仍在尝试弄清楚这是如何工作的.

I'm still trying to figure out how this works.

推荐答案

我认为问题在于您将 stringToSign 变量转换为小写.resourceId 有一些大写字母,在这个过程中会被转换.

I think the problem is that you are converting the stringToSign variable to lower case. And the resourceId has some capital letters which are converted in the process.

这篇关于Cosmos db Rest API - 错误 401 未经授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆