I am trying to use a header token with axios. However I am presented with a CORS error as I am clearly not passing over the token correctly (moving to a not authorized feed works)
Here is my http-common.js file
const token = `08E1B4C220E671AC6A48`
// my user app token from micro.blog 08E1B4C220E671AC6A48
export const HTTP = axios.create({
// baseURL: 'https://micro.blog/feeds/adamprocter.json'
baseURL: 'https://micro.blog',
headers: {
Authorization: `Bearer ${token}`
}
})
and here is my Timeline.vue component
import { HTTP } from '#/http-common'
export default {
components: {
MicroPosts
},
data() {
return {
posts: []
}
},
created() {
// no auth get = HTTP.get('')
HTTP.get('/account/verify')
.then(response => {
//console.log(response.data)
this.posts = response.data.items
})
.catch(error => {
console.log('caught error' + error.response)
})
}
}
The URL is correct but the token is failing (I believe)
POST /account/verify — Accepts an app token (which I have set up) and returns an auth token and other details.
This is the API documentation which is a little sparse but
http://help.micro.blog/2017/api-json/
http://help.micro.blog/2018/api-authentication/
I am sure it is something obvious, any help much appreciated.
The documentation says /account/verify accepts POST. You are sending a GET.
Related
I am calling an API defined using RTK Query, within a React Native + Redux Toolkit + Expo app. This is secured with an authentication / authorization system in place i.e. access token (short expiration) and refresh token (longer expiration).
I would like to avoid checking any access token expiration claim (I've seen people suggesting to use a Redux middleware). Rather, if possible, I'd like to trigger the access token renewal when the API being requested returns a 403 response code, i.e. when the access token is expired.
This is the code calling the API:
const SearchResults = () => {
// get the SearchForm fields and pass them as the request body
const { fields, updateField } = useUpdateFields();
// query the RTKQ service
const { data, isLoading, isSuccess, isError, error } =
useGetDataQuery(fields);
return ( ... )
the RTK Query API is defined as follows:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
import * as SecureStore from "expo-secure-store";
import { baseUrl } from "~/env";
export const api = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({
baseUrl: baseUrl,
prepareHeaders: async (headers, { getState }) => {
// retrieve the access_token from the Expo SecureStore
const access_token = await SecureStore.getItemAsync("access_token");
if (access_token) {
headers.set("Authorization", `Bearer ${access_token}`);
headers.set("Content-Type", "application/json");
}
return headers;
},
}),
endpoints: (builder) => ({
getData: builder.query({
// body holds the fields passed during the call
query: (body) => {
return {
url: "/data",
method: "POST",
body: body,
};
},
}),
}),
});
export const { useGetDataQuery } = api;
I understand that when the API returns isError = true and error = something 403 I need to renew the access token within the Expo SecureStore (and there's a function already in place for that). However I have no idea about how can I query the RTKQ API again, on the fly, when it returns a 403 response code, and virtually going unnoticed by the user.
Can someone please point me in the right direction?
I got the hang of it, massive thanks to #phry! I don't know how I could have missed this example from RTKQ docs but I'm a n00b for a reason after all.
This being said, here's how to refactor the RTKQ api to renew the access token on the fly, in case some other react native beginner ever has this problem. Hopefully this is a reasonable way of doing this
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
import * as SecureStore from "expo-secure-store";
import { baseUrl } from "~/env";
import { renewAccessToken } from "~/utils/auth";
// fetchBaseQuery logic is unchanged, moved out of createApi for readability
const baseQuery = fetchBaseQuery({
baseUrl: baseUrl,
prepareHeaders: async (headers, { getState }) => {
// retrieve the access_token from the Expo SecureStore
const access_token = await SecureStore.getItemAsync("access_token");
if (access_token) {
headers.set("Authorization", `Bearer ${access_token}`);
headers.set("Content-Type", "application/json");
}
return headers;
},
});
const baseQueryWithReauth = async (args, api) => {
let result = await baseQuery(args, api);
if (result.error) {
/* try to get a new token if the main query fails: renewAccessToken replaces
the access token in the SecureStore and returns a response code */
const refreshResult = await renewAccessToken();
if (refreshResult === 200) {
// then, retry the initial query on the fly
result = await baseQuery(args, api);
}
}
return result;
};
export const apiToQuery = createApi({
reducerPath: "apiToQuery",
baseQuery: baseQueryWithReauth,
endpoints: (builder) => ({
getData: builder.query({
// body holds the fields passed during the call
query: (body) => {
return {
url: "/data",
method: "POST",
body: body,
};
},
}),
}),
});
export const { useGetDataQuery } = apiToQuery;
so basically under guidance of the Spotify WebAPI doc I am trying to request an access token via Client Credentials method. Spotify API Doc. I want to use a regular HTTP fetch request, I can not use any 3rd party libraries. I am getting a 400 return status error response: {error: "unsupported_grant_type", error_description: "grant_type parameter is missing"}. However I believe my request should be formated correctly for its grant type. I have looked at tons of articles, MDN doc, and the Spotify doc and I can not figure out why this is not working. I will include the code which I have obviously taken the api keys out of but they are correct. Link to code.
import React, { Component, useState , useEffect } from 'react';
//Custom IMPORTS:
import '../PageCss/HeaderSection.css'
const Spotify = () => {
const [baseUrl, setBaseUrl] = useState("https://accounts.spotify.com/api/token");
const [token, setToken] = useState([]);
const [currentStatus, setStatus] = useState(false);
const client_id = '';
const client_secret = '';
const data = { grant_type: 'client_credentials' };
useEffect(() => {
fetch(baseUrl,
{
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Basic ' + (client_id + ':' + client_secret).toString('base64')
},
redirect: 'follow',
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
return Promise.reject(new Error("Response Error!"));
}
else {
return response.json();
}
})
.catch((err) => {
console.log(err);
})
.then((json) => {
try {
setToken(json.results);
setStatus(true);
console.log("TOKEN:" + token)
}
catch
{
return Promise.reject(new Error(`State Error!: Data: ${token} , Connection:${currentStatus}`));
}
})
.catch((err) => {
console.log(err);
})
}, [baseUrl]);
return (
<div >
</div>
)
};
export default Spotify;
My application is a react app, hosted on GitHub. It's a fully functioning site and everything else is working fine. My other API fetch calls are working fine so I know this one must have an issue in it. The only line of code giving me an error is this 400 status from the fetch request.
Hey so I actually got the inital token request to work with this code:
fetch(baseUrl,
{
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
Inspired by the OAuth doc and some more researching. It works now and I have a token from Spotify.
Good evening everyone, here I have a problem with my interceptor in VueJS. I don't understand where my problem comes from, and I'm pulling my hair out...
I've watched several tutorials, I've watched several topics on stackoverflow, but I don't understand what's going on at all.
When I put a debugger on, it's triggered, but when I switch to "axios.interceptors" it tells me that axios is undefined, it's incomprehensible...
import axios from 'axios';
debugger;
axios.interceptors.response.use(function (response) {
console.log(response);
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
console.log(error);
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
const token = localStorage.getItem('token');
export default axios.create({
baseURL: process.env.VUE_APP_URL_API,
headers: {
Authorization: `Bearer ${token}`
}
})
The code above is called in my VueX Store.
import Http from "../../api/http";
export default {
state: {
customers: {},
customer: {},
},
getters: {
customers: state => state.customers,
},
mutations: {
SET_CUSTOMERS(state, customers) {
state.customers = customers;
}
},
actions: {
loadCustomers({commit}) {
Http.get('/customers').then(result => {
commit('SET_CUSTOMERS', result.data.data );
}).catch(error => {
throw new Error(`API ${error}`);
});
}
}
};
I want to trigger http code 401 to logout my user and destroy the token in the browser.
If anyone could help me, I would be delighted, thank you very much.
Regards,
Christophe
As shown in the interceptor docs, just below the example interceptors, if you use an instance, you have to add the interceptor to it:
import axios from 'axios';
const token = localStorage.getItem('token');
const instance = axios.create({
baseURL: process.env.VUE_APP_URL_API,
headers: {
Authorization: `Bearer ${token}`
}
})
instance.interceptors.response.use(function (response) {
console.log(response);
// Any status code within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
console.log(error);
// Any status codes outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
export default instance;
For people which are wondering how the issue has been solved, there is my code :)
success.js
export default function (response) {
return response
}
failure.js
import router from 'vue-router'
export default function (error) {
switch (error.response.status) {
case 401:
localStorage.removeItem('jwt.token')
router.push({
name: 'Login'
})
break
}
return Promise.reject(error)
}
adding this to main.js
const token = localStorage.getItem('jwt.token')
if (token) {
axios.defaults.headers.common.Authorization = token
}
create api.js which is my client for all the request, so my request are always passing by this.
import axios from 'axios'
import success from '#/interceptors/response/success'
import failure from '#/interceptors/response/failure'
const api = axios.create({
baseURL: process.env.VUE_APP_URL_API
})
api.interceptors.request.use((config) => {
const token = localStorage.getItem('jwt.token')
config.headers.Authorization = `Bearer ${token}`
return config
})
api.interceptors.response.use(success, failure)
export default api
I hope it will be usefull :)
I am looking for way to access cookie in my nuxt fetch. Here is my code;
async fetch() {
const { store, route } = this.$nuxt.context
const { data } = await axios.get(
`${process.env.baseUrl}/user-saved-homes/?ordering=${route.query.ordering}`,
{
headers: {
Authorization: 'Token ' + my_token,
},
}
)
store.commit('ADD_SAVED_HOMES', data.results)
},
I need fetch because I was access to $fetchState.pending. But I have tried looking for a way to access cookie in the nuxt fetch, but I haven't found any. Please, I need help here
Since fetch by default runs on the server, I can't use js-cookies(javascript library), to get the token. So the best way to make this happen is for nuxt fetch to run on the client side.
So adding fetchOnServer: false enabled me to use js-cookies to get the token
so my code is now;
<script>
import axios from 'axios'
import Cookies from 'js-cookies'
export default {
async fetch() {
const { store, route } = this.$nuxt.context
const { data } = await axios.get(
`${process.env.baseUrl}/user-saved-homes/`,
{
headers: {
Authorization: 'Token ' + Cookies.getItem('token'),
},
}
)
store.commit('ADD_SAVED_HOMES', data.results)
},
fetchOnServer: false,
}
I'm using VueSession in my project. I created a login component and I'm passing data to my backend (Django, returns JWT token). Here is my problem. My login works fine, it returns JWT but when I want to get data from other endpoints I'm getting error 401 (Authentication credentials were not provided). When I'm using curl in my terminal everything works fine.
curl -X POST -d "username=test&password=test" http://localhost:8000/api/token/auth/
it returns token
curl -H "Authorization: JWT <my_token>" http://localhost:8000/protected-url/
and it returns data from website
Here is what I set up in my Vue project.
Login.vue
<script>
import Vue from 'vue'
export default {
name: 'Login',
data () {
return {
username: '',
password: ''
}
},
methods: {
login: function (username, password) {
let user_obj = {
"username": username,
"password": password
}
this.$http.post('http://192.168.1.151:8000/api/token/auth', user_obj)
.then((response) => {
console.log(response.data)
this.$session.start()
this.$session.set('jwt', response.data.token)
Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token
// this.$router.push('/')
})
.catch((error_data) => {
console.log(error_data)
})
}
}
}
</script>
HereIWantUserGETRequest.vue
<script>
export default {
data() {
return {
msg: "Welcome",
my_list: []
}
},
beforeCreate() {
// IF SESSION DOESN'T EXIST
if (!this.$session.exists()) {
this.$router.push('/account/login')
}
},
mounted() {
this.getData()
},
methods: {
getData: function() {
this.$http.get('http://192.168.1.151:8000/api/user/data')
.then((response) => {
console.log(response.data)
this.my_list = response.data
})
.catch((error_data) => {
console.log(error_data)
})
}
}
}
</script>
And of course I set up VueSession and VueResource in main.js
import VueSession from 'vue-session'
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.use(VueSession)
Edit
Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token
with
Vue.http.headers.common['Authorization'] = 'JWT ' + response.data.token
Hope it will help you
You don't actually store your jwt token anywhere in your browser (with a cookie or a localStorage). Therefore Vue has the token in memory only for the runtime of that page (in the sense of a one page app) you've request your jwt token in. According to the github docs of VueSession the option to store the token in your browser is false by default. Just set it to true like this:
#main.js
var options = {
persist: true
}
Vue.use(VueSession, options)
I personally don't use this library. I usually do it from scratch using axios, Vuex and localStorage. It's really not that difficult, the pattern is described pretty well here.
The problem was with this line Vue.http.headers.common['Authorization'] = 'JWT ' + response.data.token. To fix it I needed to at this to my main.js file:
if (this.$session.exists()) {
var token = this.$session.get('jwt')
console.log(token)
Vue.http.headers.common['Authorization'] = 'JWT ' + token
}
And now it's working.