Am using Nextjs for front end and Asp.Net core as a backend (API). I use JWT authentication to access the endpoints from Next Js using axios. Am also setting sessions on the backend to store user data. The problem is that HttpContext.Session is always null. The following is a sample of code I use:
axios.post(`https://localhost:44301/Home/GetValues`, { },
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
withCredentials: true
}
)
.then(res => {
console.log("Values", res.data);
})
.catch(err => console.log(err));
With Postman am able to access the HttpContext.Session. That means the Nextjs is not sending session cookies set by the Asp.net core.
Related
Here is my code:
axios
.post(
'https://app.adhg.ashdg/m/api/business/get-business',
{
'gid': getgid,
},
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
// handle success
alert(JSON.stringify(response.data));
})
.catch(function (error) {
// handle error
alert(error.message);
});
I am implementing Axios post request in my React Native application. I want to send formurlencoded parameters along with the header called cookie.
In cookie I am storing AWS token value to send. But I am not getting the response, it says cookie is not sent. The same URL with params working perfectly in Postman. How can I pass cookie in the header?
Try something like this Cookie: name=value.
Mozilla Web Docs
I am using the following code from react-native mobile application to make a social authentication call to dj-rest-auth local link. However my Facebook authentication succeeds each time and then the fetch (or axios) local API call executes, which runs perfectly for the first time/run returning me the token but thereafter on every other runs, it gives me an error saying missing or invalid csrf token. I can't used the Django docs getCookie function as it gives Document error since this is a react-native mobile application. Please guide how to properly have API calls using csrf from the mobile app, with the code being used below (which is inside an async function):
fetch(
"http://192.168.1.102:8080/dj-rest-auth/facebook/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken',
body:JSON.stringify({access_token:resolvedToken})
}
)
.then(resp => resp.json())
.then(data => {
console.log(data);
}
)
.catch(error => console.log(error))
The logout function also give the missing or invalid csrf error, which is written below for reference:
async function Logout() {
fetch(
"http://192.168.1.102:8080/dj-rest-auth/logout/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken'
}
)
.then(resp => resp.json())
.then(data => {console.log(data)})
.catch(error => console.log(error))
}
The issue above is resolved by removing "Session Authentication" from your default REST authentication classes in settings.py and keeping the "Basic Authentication" and "Token Authentication" enabled.
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
Source: https://github.com/Tivix/django-rest-auth/issues/164#issuecomment-860204677
I tried to send data to line notify server by axios and it fail
I have tried 2 version of code. as shown below
version 1 :
axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
data: 'message="from vue"',
config: {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
}
},
Authorization: "Bearer [my token]"
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
console.log(response);
});
response is
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
and version 2 is :
axios
.post("https://notify-api.line.me/api/notify", "message=from vue", {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer [my token]"
}
})
.then(response => {
console.log(response);
});
response is
Preflight response is not successful
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
What wrong with is
but I have tried in postman it work fine
Oh I am too familiar with this. Heres an explanation on stackoverflow as to why your request works with postman but not in browser. Long story short browsers send a preflight options check that will ask the server if the action you're about to perform is allowed. Postman does not. Usually the "Access-Control-Allow-Origin": "*" header is sent by the server to the browser not the other way around.
Inside the docs for LINE Notify you can find:
POST https://notify-api.line.me/api/notify
Sends notifications to users or groups that are related to an access token.
If this API receives a status code 401 when called, the access token will be deactivated on LINE Notify (disabled by the user in most cases). Connected services will also delete the connection information.
Requests use POST method with application/x-www-form-urlencoded (Identical to the default HTML form transfer type).
My guess is that your access_token might have been deactivated. Try requiring a new access token and doing the request again.
I think it is impossible to connect directly to the external url for the axios cuz ajax is basically for the inner data network. But you might have a controller if you do a web project, so you can just use your controller language to make a connection with line notify. In my case, I made a rails project and used axios in the vue.js, so I made a link like this.
View(axios) => Controller(Ruby) => LineAPI
me currently work on this too.
I did my app with node js.
My way below is for your reference, it works well.
const axios = require('axios');
const querystring = require('querystring');
axios({
method: 'post',
url: 'https://notify-api.line.me/api/notify',
headers: {
'Authorization': 'Bearer ' + 'YOUR_ACCESS_TOKEN',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
data: querystring.stringify({
message: 'something you would like to push',
})
})
.then( function(res) {
console.log(res.data);
})
.catch( function(err) {
console.error(err);
});
I try it works.
async function test() {
const result = await axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer [token]",
},
data: 'message=你好哇'
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
}
test();
I think you can check response on chrome debugger network.
or provide more information, thx.
I recently implement Axios in my react native app. The problem I am facing is whenever I add authorization header with the request, it returns 400 while the same request with same Auth token is working fine with Postman. What can be the issue?
axios.get(EndPointURL, {
headers: {
Authorization: BearerToken
}
})
.then(result => {
console.log(result);
})
.catch(reason => {
console.log(
reason
);
});
}
Are you sure that BearerToken is the same as the token you're using in PostMan? Seems to me you need you're not adding Bearer prefix that's required by OAuth2
Example:
headers: {
Authorization: `Bearer ${BearerToken}`
}
I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.
I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:
methods: {
getUser () {
this.$http.get('http://localhost:8000/api/user',
{
headers: {
'Authorization': 'Bearer eyJ0e.....etc',
'Accept': 'application/json'
}
}).then((response) => {
this.name = response.data.name
});
},
However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.
Based on the vue-resource readme I am trying this in my main.js:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
And then back in my component I now just have:
this.$http.get('http://localhost:8000/api/user').then((response) => {
this.name = response.data.name
});
Problem:
When I specify the headers in the get itself, I get a successful response, but when I pass them through the interceptor I get back a 401 Unauthorized from the server. How can I fix this to respond successfully while using the interceptor?
Edit:
When I use dev-tools to view the outgoing requests I see the following behavior:
When making the request by supplying the headers to $http.get, I make a successful OPTIONS request and then a successful GET request with the Authentication header being supplied to the GET request.
However, when I remove the headers from the $http.get directly and move them to the interceptor, I only make a GET request and the GET does not contain the Authentication header, thus it comes back as a 401 Unauthorized.
It turns out my problem was the syntax for which I was setting the headers in the interceptor.
It should be like this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer eyJ0e.....etc')
request.headers.set('Accept', 'application/json')
next()
})
While I was doing this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
Add this option:
Vue.http.options.credentials = true;
And use the interceptors for global way:
Vue.http.interceptors.push(function(request, next) {
request.headers['Authorization'] = 'Basic abc' //Base64
request.headers['Accept'] = 'application/json'
next()
});