Skip to content

Instantly share code, notes, and snippets.

@Destaq
Created July 20, 2022 16:35
Show Gist options
  • Save Destaq/d293d0fd5f9805cbf2f7f4a58a2f6d6b to your computer and use it in GitHub Desktop.
Save Destaq/d293d0fd5f9805cbf2f7f4a58a2f6d6b to your computer and use it in GitHub Desktop.
Nuxt 2 + Flask — full, working custom refresh scheme using cookies from flask-jwt-extended
@app.after_request
def refresh_expiring_jwts(response):
"""
Here we are supporting the implicit cookie refresh mechanism.
If a not-yet-expired access cookie (token) is sent with a request, it will be replaced
with one that is newly created, also for two weeks.
(Note that this will not work just by opening the app, the user also needs to do some actions).
"""
try:
exp_timestamp = get_jwt()["exp"]
now = datetime.now(timezone.utc)
target_timestamp = datetime.timestamp(now + timedelta(days=7))
if target_timestamp > exp_timestamp:
access_token = create_access_token(identity=get_jwt_identity())
access_token = "Bearer " + access_token
response.set_cookie("auth._token.cookie", access_token, samesite="None", secure=True) # latter two required to actually set
# set_access_cookies(response, access_token)
return response
except (RuntimeError, KeyError) as e:
# Case where there is not a valid JWT. Just return the original respone
return response
export default function ({ $axios, app, store }) {
$axios.onRequest(config => {
if (store.state.auth.loggedIn) {
config.headers.common['Authorization'] = app.$auth.$storage._state["_token.cookie"]
}
})
}
// default vuex store
export const state = () => ({});
methods: {
async logIn() {
try {
await this.$auth.loginWith("cookie", {
data: {
email: this.email,
password: this.password,
},
});
this.$router.push("/");
} catch (error) {
console.log(error);
this.showLoginError = true;
}
},
}
server: {
port: 3000,
host: "127.0.0.1", // run on this port so that cookies are set
},
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
"@nuxtjs/axios",
"@nuxtjs/auth-next",
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
baseURL: "http://127.0.0.1:5000/",
withCredentials: true,
credentials: true,
headers: {
common: {
"Content-Type": "application/json",
},
},
},
auth: {
localStorage: false,
redirect: {
login: "/login",
logout: "/login",
callback: "/login",
},
strategies: {
local: false,
cookie: {
token: {
property: "token",
required: true,
type: "Bearer",
},
user: {
property: "user",
autoFetch: true,
},
endpoints: {
login: { url: "/api/auth/login", method: "post" },
logout: { url: "/api/auth/logout", method: "post" },
user: { url: "/api/auth/user", method: "get" },
},
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment