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));
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.
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
})
})
Basic authentication requires you to add a header to the ajax request which gets send to the GitHub API. This is already answered in use-basic-authentication-with-jquery-and-ajax.
Related
I am trying to request an authorization token from Amadeus using axios by following this documentation. However, I'm quite unexperienced with the axios library and am failing to build the request correctly, because I get this response:
code: 38187
error: "invalid_request"
error_description: "Mandatory grant_type form parameter missing"
title: "Invalid parameters"
The curious thing is that I tried to simulate the same request with curl and it worked, so I'm really puzzled as to where my error is. Below is my curl request
curl -v "https://test.api.amadeus.com/v1/security/oauth2/token"
-H "Content-Type: application/x-www-form-urlencoded"
-d "grant_type=client_credentials&client_id=xxxxxx&client_secret=xxxxxx"
Here is my JavaScript code, please let me know if you are able to notice the difference! Thanks in advance
async getAmadeusKey() {
const response = await axios({
url: "https://test.api.amadeus.com/v1/security/oauth2/token",
method: 'post',
headers: {
'Content-Type': 'x-www-form-urlencoded'
},
data: {
grant_type: 'client_credentials',
client_id: CLIENT_ID, // of course both these constants are defined outside of this scope
client_secret: CLIENT_SECRET,
}
});
console.log(response.data);
}
Edit: I had an error with the header, but the response misidentified the error on my request even after applying the fix suggested below. Note that the header should have Content-Type application/x-www-form-urlencoded
By default, axios serialises the data parameter as JSON. Since you want to send a x-www-form-urlencoded request, you will have to serialize the data parameter in that format instead.
If you're targeting modern browsers only, you can use URLSearchParams like so:
const data = new URLSearchParams({
grant_type: 'client_credentials',
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
})
const response = await axios({
... // your code here
data,
})
I am trying to use the Basic Authorization method that accepts username and password. I am working in React, using a fetch. It does not seem to work. It sends status 401 Unauthorized. I've no two-factor authentication. And yes, I have used PAT but I want to authenticate using username:password method. Kindly look at the code:
fetch("https://api.github.com/user", {
method: "GET",
headers: {
Authorization: `Basic ${btoa(`${username}:${password}`)}`,
"Content-Length": 0,
},
}).then((response) => response.status);
I'm in the process of attempting to verify a JWT access_token against OneLogin's api as described here. My code is as follows:
const client_id = MY_CLIENT_ID
const client_secret = MY_CLIENT_SECRET
const token = MY_ONE_LOGIN_JWT_ACCESS_TOKEN
axios
.post(
"https://my-endpoint-dev.onelogin.com/oidc/2/token/introspection",
{ token, client_id, client_secret, token_type_hint: "access_token" },
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
)
.then((response) => {
console.log("response");
console.log(response);
})
.catch((err) => {
console.log("err");
console.log(err);
});
The endpoint appears to work fine, in fact when the JWT has become expired it gives me an error stating as such and I need to update the token I'm passing along. However, whenever I make a standard request as shown above with valid credentials and tokens I get the following error response:
{error: "invalid_request", error_description: "no client authentication mechanism provided"}
There's no documentation on the provided page that describes what is wrong with the request when that error is received. From the documentation, so far as I can tell, my request is formatted correctly.
I have verified that the Token Endpoint in OneLogin is set to POST, so my assumption that the client_secret should be in the body is documented as correct (though I did try it as Basic just to verify):
I've attempted searching for a solution, but the only thing close I've found advises that the Content-Type header may not be supplied. I've made sure to add that to the list of headers and have verified it shows up in the request, but still the error persists.
Any thoughts to what I may be missing here?
EDIT:
Attempted to do a cURL request and received a 200 response back with the same information. Leading me to believe it's something with the axios call that I have incorrect.
I get this message when I don't provide either the client_id or the client_secret. Hopefully you can validate that you are actually sending both in your request. Maybe you can try the request via postman to double check.
I ran into the same issue and finally figured out you have to turn the data into a query string: https://axios-http.com/docs/urlencoded
For example:
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
I'm trying to post an image to my API.
Logging in works great and authentication works on that part.
Then when I try to authenticate for the POST request, using JWT bearer token that's returned from my identity server I get a 401 unauthorized.
Using the same id_token in postman and posting the same image works and gives me a ``200 success` along with storing the posted image.
Is there something wrong with the way I'm setting up the fetch?
const data = new FormData()
console.log(user)
event.preventDefault()
data.append("file", image, user.profile.unique_name.slice + ".png")
fetch(devUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${user.id_token}`
},
body: data
})
.then(response => {
if (response.status === 200) {
setSuccessUpload(true)
}
})
UPDATE:
I'm incompetent and it turns out I was using id_token and not access_token like you should..
I'm looking for example of fetch() method to call secured API (I use Azure AD B2C)
To be specific I I don't know how should my headers look like.
Calling API using Postman with authorization works.
My API is hosted on localhost:44320 I didn't deploy it.
In React I use 'react-azure-adb2c' library and it also works. I can log in and after that I'm getting token with all claims which I need.
var token = auth.getToken(); //here is the token which is correct
fetch("https://localhost:44320/api/worker/", {
method: "GET",
headers: {
Authorization: token,
Accept: "application/json",
Host: "localhost:44320"
}
})
.then(res => res.json())
.then(json => this.setState({ listOfWorkers: json.results }));
}
You specify the header as Authorization: Bearer token-value-here.
So Authorization: 'Bearer ' + token in your case.