7

I'm using a Javascript to do Basic Authentication with GitHub. For example, the following shell command gets a token from Github:

    curl -i -u uaername:password -k -d "{\"scopes\": [\"repo\"]}" https://api.github.com/authorizations

How do you achieve that with jQuery and AJAX?

0

2 Answers 2

7

Including Basic Auth Data in HTTP Headers with jQuery

You can include basic auth details in the header using the Authorization field. You already understand how jQuery works. This snippet has the bits you're missing:

    let auth = btoa(username + ":" + password);

    jQuery.ajax({
        url: ...,
        headers: { Authorization: "Basic " + auth }
        ...
    });

Note: btoa and atob (pronounced B to A and A to B) are builtin functions, and convert to and from Base64. See the MDN docs for more information.

Sign up to request clarification or add additional context in comments.

2 Comments

useful snippet too if you are using a personal access token, thanks
Is this safe to do in client-side JavaScript?
5

Are you asking whether there is a way to get an oAuth token purely from the client side? If so, the answer is no.

But, you have some work arounds.

Github.js: https://github.com/michael/github

Gatekeeper is an open source server side component which can help with oAuth tokens management:

https://github.com/prose/gatekeeper

You could also use something like Firebase with simple login and in this case you don't need to manage any server side services:

https://www.firebase.com/docs/security/simple-login-github.html

3 Comments

He asked specifically about basic auth, which you can definitely do from a browser. There's Octokit JS libraries that do it.
Yes, this is correct that he asked about basic auth, but I don't think you can use basic auth to retrieve an oAuth token (I think he needs that here, no?), even with these libraries. I believe you have to map the callback to an actual server (not just a web browser) which means the pure client side JS won't work.
No. You can just include the username and password in the request headers. You never need oAuth.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.