Created
March 26, 2019 20:57
-
-
Save MiguelSavignano/c954b17c33ad538695f1b7a9f0cd1cdb to your computer and use it in GitHub Desktop.
axios http auth client with refresh token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; | |
import createAuthRefreshInterceptor from "axios-auth-refresh"; | |
import config from "../config"; | |
export const generateAuthHeader = authToken => | |
`Token api_key=${config.API_KEY}, auth_token=${authToken}`; | |
interface Storage { | |
get: (key: string) => Promise<string>; | |
set: (key: string, data: string) => Promise<string>; | |
} | |
export class HttpAuth { | |
http: AxiosInstance; | |
constructor(private storage: Storage) {} | |
async init() { | |
if (this.http) return this.http; | |
const authToken = await this.storage.get("AUTH_TOKEN"); | |
const refreshToken = await this.storage.get("REFRESH_TOKEN"); | |
this.http = axios.create({ | |
baseURL: `${config.API_HOST}/api/`, | |
headers: { | |
"Content-Type": "application/json", | |
Authorization: generateAuthHeader(authToken) | |
} | |
}); | |
createAuthRefreshInterceptor(this.http, async failedRequest => { | |
const response = await this.http.post("/users/refresh", { | |
refresh_token: refreshToken | |
}); | |
failedRequest.response.config.headers[ | |
"Authorization" | |
] = generateAuthHeader(response.data.auth_token); | |
await this.storage.set("REFRESH_TOKEN", response.data.refresh_token); | |
await this.storage.set("AUTH_TOKEN", response.data.auth_token); | |
return Promise.resolve(); | |
}); | |
return this.http; | |
} | |
async get(url: string, config?: AxiosRequestConfig) { | |
await this.init(); | |
return this.http.get(url, config); | |
} | |
async post(url: string, data?: any, config?: AxiosRequestConfig) { | |
await this.init(); | |
this.http.post(url, data, config); | |
} | |
async put(url: string, data?: any, config?: AxiosRequestConfig) { | |
await this.init(); | |
this.http.put(url, data, config); | |
} | |
async delete(url: string, config?: AxiosRequestConfig) { | |
await this.init(); | |
this.http.delete(url, config); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment