Token authentication with C# Web Api and axios - asp.net-web-api

I am implementing a login. I can send a post request to the endpoint token in Postman but not in axios.
Axios function:
axios({
method: 'post',
url: 'http://localhost:20449/token',
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
data: {
'grant_type': 'password',
'username': user.username,
'password': user.password
}
}).then(resp => {
console.log(resp)
commit(AUTH_SUCCESS, resp)
dispatch(USER_REQUEST)
resolve(resp)
})
I get the error
"unsupported_grant_type"

I found a solution. Axios uses application/json by default when data is an object. It did not worked even after adding application/x-www-form-urlencoded in header. So I downloaded the package qs (npm install qs --save). I imported the package and use the axios command below:
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });

Related

CORS error when add params (vue and laravel)

i have code axios :
var url =`laporan_type=${typeLaporan}&provinsi_id=${id_provinsi}&id_kabkota=${id_kabkota}&id_kecamatan=${id_kecamatan}&year=${year}&month=${month}`
axios({
method: 'get',
url: `${simkah}/laporan/reportWord?${url}`,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
responseType: "blob"
}).then(
(response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
}
).catch((error) => {
console.log(error);
});
and i get error CORS. Can you help me pls ( i have seen many topic and i still don't understand why it is not working
CORS is to be set on the backend, Ask your backend laravel developer to create a CORS middleware and pass that in API routes. So whenever you send the request from API just send all the headers you'll get a successful response.
To create middleware in laravel just followed any suitable tutorials or create it on your own.
Middleware tutorial:
https://www.stackhawk.com/blog/laravel-cors/

Authorization failed on a fetch request to the Brawl Stars API

I'm trying to send a get request with fetch API to ask the brawl stars API server. I've created an API KEY associated with my IP address. I've tried everything, but I got a 403 response from the server.
Here is my code :
const url = 'https://api.brawlstars.com/v1/players/...';
const token = '...';
const headers = new Headers({
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
});
const options = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
};
fetch(url, options)
.then(response => response.json())
.then(console.log)
.catch(console.error);
In the console there is the message : No 'Access-Control-Allow-Origin' header is present on the requested resource because of cors policy.
When I test the request on Insomnia, it works well !
I had a problem with the Brawlstars API a little while back when I was making a Brawlstars command for my Discord bot. I was able to get the API to work however with the following code.
const playerurl = 'https://api.brawlstars.com/v1/players/';
const getJSON = async url => {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer <yourapitoken>',
},
});
if(!response.ok) {throw new Error(response.statusText);}
const data = await response.json();
return data;
}
catch(error) {
return error;
}
};
getJSON(playerurl).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
I hope this works for you!

Jhipster Spring backend - Social login & React Native frontend

I have created Spring as backend and enabled social login for google authentication. /signin/google is the endpoint with a method POST and content type is application/x-www-form-urlencoded with scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email.
Postman client works perfectly fine if i invoke the above mentioned endpoint from postman client(Google chrome app) it gives me 200 status code and JSESSIONID and i am able to invoke the other secure api.
but for react native i am unable to execute it. Help would be highly appreciated. Mentioned below is the function that i am using to trigger google signin.
googleSignin = () => {
var data = 'scope=' + encodeURIComponent('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email');
axios({
url: baseUrl + 'signin/google',
method: 'POST',
data: data,
config: {
headers:
{
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': true
},
credentials: "same-origin"
},
withCredentials: true
})
.then(res => {
console.log('googleSignin res() ---> ', res.headers);
})
.catch(e => console.log(e));
};
It always gives me CORS error policy. mentioned below is the cors configuration on the backend.
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "Access-Control-Allow-Headers, Authorization, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
exposed-headers: "Authorization,Link,X-Total-Count"
allow-credentials: true
max-age: 1800
and screenshot is the error:
This is a cross-domain issue. After jQuery 1.5.0 and later, the cross-domain was blocked. As a result, the following error occurs when requested by ajax:
Try this code.
const options = baseUrl + 'signin/google'
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = [removed].protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.post(
options,
function (response) {
console.log(">>>> " + JSON.stringify(response));
});

Request fails after retrieving JWT token

I am using Django JWT with DRF and Vue Js with axios. When a user logs in I retrieve and store the token in local storage which I have verified to work. I then redirect to a new page where I make another request to get data. Every time I redirect to this page I get a 401 not authorized and when I refresh the page it works fine. I checked to make sure the token is stored before making the second request which it is. I attempt to get the data on the redirected page in the created hook. I also create an axios instance to deal with the headers and use a base route and then import that into the files where needed, I am not sure if that has something to do with it. This also only happens when the token has expired and you try to retrieve a new one. Should I be refreshing the token instead of trying to get a new one?
Axios instance
import axios from 'axios'
export default axios.create({
baseURL: `http://127.0.0.1:8000/`,
headers: {
'Content-Type': 'application/json',
Authorization: 'JWT ' + localStorage.getItem('token')
},
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: true
})
Edit
api.js
import axios from 'axios'
export default axios.create({
baseURL: `http://127.0.0.1:8000/`,
headers: {
'Content-Type': 'application/json',
Authorization: 'JWT ' + localStorage.getItem('token')
},
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: true
})
AppLogin.vue
Confirm is triggered by clicking a login button
confirm: function() {
API.post("accounts/login/", {
email: this.email,
password: this.password,
})
.then(result => {
console.log(result.data.token);
this.token = result.data.token;
localStorage.setItem("token", this.token);
this.getUserInfo()
})
.catch(error => {
console.log(error);
});
},
getUserInfo: function(){
axios.get("http://127.0.0.1:8000/userinfo/get/", {
headers: {
'Content-Type': 'application/json',
Authorization: 'JWT ' + this.token
}
})
.then(response => {
console.log(response.data.pos);
var pos = response.data.pos;
this.reroute(pos);
})
.catch(error => {
console.log(error);
});
},
reroute(pos) {
if (pos == "owner") {
this.$router.push({ path: "/bizhome" });
} else {
this.$router.push({ path: "/" });
}
}
BizHome.vue
This is the page that login redirects to on success
created: function() {
this.getLocations();
},
methods: {
getLocations() {
API.get("business/")
.then(response => {
this.biz = response.data;
})
.catch(error => {
console.log(error);
});
API.get("locations/")
.then(response => {
this.bizLocations = response.data;
})
.catch(error => {
console.log(error);
});
},
}
solution
Using some advice that I had gotten from YuuwakU below, I added the headers directly to the get calls in the getLocations method to overwrite the axios instance headers. It appeared that the new page loaded before the token was updated in the instance. One drawback to this solution though is that I now have to directly add the headers to all the calls I make. The headers in the instance never to update. I did add API.defaults.headers.common['Authorization'] = 'JWT ' + result.data.token; to the confirm method on successful retrieval of the token which should have updated the token for the instance. This did not work for me, if anyone has any ideas I would be interested in hearing them
edit 2
I did figure out why the axios instance did not update it is because I was trying to get the token from local stroage in api.js and it was overriding it. Now it works but the token is not persistent so this is not ideal as well. I will update if I find a better solution.
Final Update
I finally figured out a good solution. I removed the authorization header from the axios instance in api.js then I removed all the headers from all the axios calls. In the confirm method upon successful login I added this line mentioned previously mentioned API.defaults.headers.common['Authorization'] = 'JWT ' + result.data.token; and also added the token to local storage. I have a verify token method that runs before pages load. In that method before I make the post request to verify the token I added API.defaults.headers.common['Authorization'] = 'JWT ' + localstorage.getItem('token'); . This allows a user to navigate aways the site and come back and still use the token if valid and does not require the headers to be set on every call.
The reason why that is happening is because an axios instance has already been created with an expired token that exists in the localStorage. So you have to make sure that the axios instance is updated with a fresh get of the token after login, otherwise you will end up using the old token until a fresh page reload. Try the following:
import axios from 'axios'
export default axios.create({
baseURL: `http://127.0.0.1:8000/`,
headers: {
'Content-Type': 'application/json',
Authorization() { // Converted to a method, similar concept to a vue data property
return `JWT ${localStorage.getItem('token')}`,
}
},
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: true
})
OR, you can even use axios interceptors as well to fetch from localStorage with each request:
// Add a request interceptor
axios.interceptors.request.use(config => {
// Do something before request is sent
config.headers = {
'Content-Type': 'application/json',
Authorization: 'JWT ' + localStorage.getItem('token')
}
return config
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

React Native getting response 400 when post to oauth/token using laravel passport

I am trying to login through oauth/tokens from my React Native project. I have tested with POSTMAN When i send the data from axios it works well. But when i try to send from my app it gives me Error: Request failed with status code 400
my code is :
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: {
client_id : '2',
client_secret : 'secret',
grant_type : 'password',
email : this.state.userEmail,
password : this.state.userPassword
}
})
.then((response) => {
console.log(response.data);
})
I've solved the problem in this way:
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
data: 'client_id=2&client_secret=secret&grant_type=password&email=' + this.state.userEmail+'&password='+this.state.userPassword
})
.then((response) => {
console.log(response.data);
})
Seems Axios have some problem to process the data in json format.
If you use Webpack you must also configure the proxy.

Resources