Manually authenticating a user in Nuxt

Viewed 448

If I have a url: <host>/login/?token=<valid_backend_token>, where valid_backend_token is an authentication token that my backend produced. Using this token, I can pretty much do anything that I want for my use case (including fetching user profile, etc.). Is there a way I can use this token to authenticate an user in Nuxt?

Currently, I tried something like this:

  mounted() {
    if (this.$route.query.token) {
      this.$axios
        .get("/profile/", {
          headers: {
            Authorization: "Token " + this.$route.query.token,
          },
        })
        .then((resp) => {
          this.$axios.setToken(this.$route.query.token, "Token");
          this.$auth.setUser(resp.data);
          this.$router.push("/");
        });
    }
  },

Of course, this doesn't authenticate my user (since $auth.loggedIn is false). $auth.user is of course set and I can visit the profile page (if I disable auth middleware). Besides $auth.loggedIn being false, my $this.axios.get/put/etc. would throw the error (even though there's no need to refresh tokens in my case and I have already set it):

ExpiredAuthSessionError: Both token and refresh token have expired. Your request was aborted.

How can I make this authentication work?

1 Answers

So I took another take, and I was able to solve the problem as follows:

Define a new strategy (starting with local scheme) in nuxt.config.js:

auth: {
  strategies: {
    local: {...},
    social: { // new strategy
      scheme: "local",
      token: {
        property: "auth_token",
        name: "Authorization",
        type: "Token",
      },
      user: {
        property: false,
      },
      endpoints: {
        login: { url: "social/token/login/", method: "post" },
        logout: { url: "auth/token/logout", method: "post" },
        user: { url: "/profile/", method: "get" },
      }
    }  
  }
  redirect: {...},
}

Then, in my page where my users land with the token in the url, I do the following:

  mounted() {
    if (this.$route.query.token) {
      this.$auth.loginWith("social", {
        data: { token: this.$route.query.token },
      });
    }
  },

At this point nuxt-auth (auth-next) handles everything for me. The endpoint social/token/login/ literally just echoes back the same token.

Related