简体   繁体   中英

Trying to set up API Management REST API Authentication w/ Node JS

My goal is to authenticate a Node.js client w/ the Azure API Management API.

I am struggling a bit here with the translating this C# example to Node.js Javascript. I've tested the C# example with my own id and key and it seems to authenticate 200 with the API, but I keep getting a 401 with my Node.js snippet.

I have a feeling that it may have to do with the way that the C# example formats the expiry ( ex={1:o} ) which is a type of Format Specifier

C# Example

source: Azure API Management REST API Authentication

using System;   
using System.Text;   
using System.Globalization;   
using System.Security.Cryptography;   

public class Program   
{   
    public static void Main()   
    {   
        var id = "12345678abcdefgh";   
        var key = "1234abcd5678asdf==";   
        var expiry = DateTime.UtcNow.AddDays(10);   
        using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))   
        {   
            var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);   
            var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));   
            var signature = Convert.ToBase64String(hash);   
            var encodedToken = string.Format("SharedAccessSignature uid={0}&ex={1:o}&sn={2}", id, expiry, signature);   
            Console.WriteLine(encodedToken);   
        }   
    }   
}

My Node.js Snippet

var util = require('util')
var crypto = require('crypto')
var generateAccessCode = function() {
    var id = "1234asdf1234asdf";
    var key = "1234asdf1234ghjk";
    const accessCodeExpireDays = 10;
    const formatString = 'SharedAccessSignature uid=%s&ex=%s&sn=%s'
    const dataToSignString = '%s\n%s';

    //create expiry string
    var today = new Date();
    var expiry = new Date();
    expiry.setDate(today.getDate() + accessCodeExpireDays);
    expiry = expiry.toISOString();

    //create hash
    var dataToSign = util.format(dataToSignString, id, expiry)
    const hash = crypto.createHmac('sha512', key)
        .update(dataToSign)
        .digest('base64');

    var encodedToken = util.format(formatString, id, expiry, hash);

    console.log(encodedToken)
}

generateAccessCode()

You may need to format the expiry date as below via Moment.js :

//create expiry string
var today = new Date();
var expiry = new Date();
expiry.setDate(today.getDate() + accessCodeExpireDays);
expiry = moment(expiry).format('YYYY-MM-DD[T]HH:mm:ss.SSSSSSS[Z]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM