Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems Github Api Authorization

I'm trying to do a authorization request with Github Api, passing the username and password. But it's not working and i'm getting 401 status code.

In the Documentation there's a part saying

To use Basic Authentication with the GitHub API, simply send the username and password associated with the account.

That's my code:

this.api
        .post('/user', { username: 'Example', password: '1234' })
        .then(res => resolve(res.data))
        .catch(err => reject(err));
like image 213
Laura Beatris Avatar asked Dec 13 '19 13:12

Laura Beatris


2 Answers

Not sure if you aim to use the Basic Authentication provided by Github API. If that's the case I think you should use the Axios auth header:

axios.get('https://example.com', {
  auth: { user: "username", password: "password" }
});

Here's what Axios docs say:

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  // Please note that only HTTP Basic auth is configurable through this parameter.
  // For Bearer tokens and such, use `Authorization` custom headers instead.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

There's another way to manually set the authorization header like this:

axios.get('https://example.com/', {
 headers: {
   Authorization: 'Basic ' + Base64.encode('username' + ':' + 'password');
 }
})

And the last note is that deprecation is coming:

Deprecation Notice: GitHub will discontinue password authentication to the API. You must now authenticate to the GitHub API with an API token, such as an OAuth access token, GitHub App installation access token, or personal access token, depending on what you need to do with the token.

Consider using tokens instead of username and password.

like image 56
Goran Stoyanov Avatar answered Sep 19 '22 18:09

Goran Stoyanov


Note that if your account has activated 2FA (two-factor authentication), then you would need to use a PAT (Personal Access Token) as your password.

curl --header 'Authorization: token INSERTACCESSTOKENHERE' 
--header 'Accept: application/vnd.github.v3.raw' 
--remote-name 
--location https://api.github.com/...

See "Passing headers with axios POST request"

const headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/vnd.github.v3.raw',
  'Authorization': 'token INSERTACCESSTOKENHERE'
}

axios.post(url, data, {
    headers: headers
  })
  .then((response) => {
    dispatch({
      type: yourEvent,
      data: response.data[0]
    })
  })
  .catch((error) => {
    dispatch({
      type: yourError
    })
  })
like image 34
VonC Avatar answered Sep 19 '22 18:09

VonC