简体   繁体   中英

how do I add api token included as a username for each HTTP request i make to an API

I am having difficulties adding my api token to make http requests on the Worksnaps API.

Here is their documentation explonation but I can't get it to work. https://www.worksnaps.com/api_docs/worksnaps_api.html

And here is my code:

// prepare the header
var headers = {
    //'Content-Type' : 'text/xml',
    //'Content-Length' : Buffer.byteLength(jsonObject, 'utf8'),
    'Authorization': 'token'
};

// options for GET
    var options_get = {
        host: 'worksnaps.com', // here only the domain name
        // (no http/https !)
        //port : 443,
        path: '/api/projects/' + project_id + '/user_assignments.xml', // the rest of the url with parameters if needed
        method: 'GET', // do GET
        headers: headers
    };

It always returns status401,which from my knoledge it means Unauthorized. Any idea?

According to the docs you provided worksnaps uses basic authentication

Every user has an API token and authentication is managed using HTTP basic authentication. In each request the API token has to be included as the username and the password is ignored (that is, only the API token is used for authenticating API requests). Example,

curl -H 'Accept: application/xml' -H 'Content-Type: application/xml' \\ -u hy192jfeh26uiew8yg43mfekb21jfenaxop912f3:ignored -d '...'

so what you're looking for is:

var auth_hash = new Buffer(token_string + ":ignored").toString('base64')
'Authorization': 'Basic ' + auth_hash

Based on RFC 6750, 2.1. Authorization Request Header Field you probably need to add "Bearer" to your header:

'Authorization': 'Bearer ' + token_string

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