无法使用django rest auth配置axios登录并获取auth令牌 [英] failed to configure axios with django rest auth to login and get auth token

查看:89
本文介绍了无法使用django rest auth配置axios登录并获取auth令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码:

import session from "./session";

export default {
  login(Username, Password) {
    return session.post("/auth/login/", { Username, Password });
  },
  logout() {
    return session.post("/auth/logout/", {});
  },
  createAccount(username, password1, password2, email) {
    return session.post("/registration/", {
      username,
      password1,
      password2,
      email
    });
  },
  changeAccountPassword(password1, password2) {
    return session.post("/auth/password/change/", { password1, password2 });
  },
  sendAccountPasswordResetEmail(email) {
    return session.post("/auth/password/reset/", { email });
  },
  resetAccountPassword(uid, token, new_password1, new_password2) {
    // eslint-disable-line camelcase
    return session.post("/auth/password/reset/confirm/", {
      uid,
      token,
      new_password1,
      new_password2
    });
  },
  getAccountDetails() {
    return session.get("/auth/user/");
  },
  updateAccountDetails(data) {
    return session.patch("/auth/user/", data);
  },
  verifyAccountEmail(key) {
    return session.post("/registration/verify-email/", { key });
  }
};

src/session.js

import axios from "axios";

const CSRF_COOKIE_NAME = "csrftoken";
const CSRF_HEADER_NAME = "X-CSRFToken";

const session = axios.create({
  xsrfCookieName: CSRF_COOKIE_NAME,
  xsrfHeaderName: CSRF_HEADER_NAME
});

export default session;

src/store/auth.js

import auth from "../api/auth";
import session from "../api/session";
import {
  LOGIN_BEGIN,
  LOGIN_FAILURE,
  LOGIN_SUCCESS,
  LOGOUT,
  REMOVE_TOKEN,
  SET_TOKEN
} from "./types";

const TOKEN_STORAGE_KEY = "TOKEN_STORAGE_KEY";

const initialState = {
  authenticating: false,
  error: false,
  token: null
};

const getters = {
  isAuthenticated: state => !!state.token
};

const actions = {
  login({ commit }, { username, password }) {
    commit(LOGIN_BEGIN);
    return auth
      .login(username, password)
      .then(({ data }) => commit(SET_TOKEN, data.key))
      .then(() => commit(LOGIN_SUCCESS))
      .catch(() => commit(LOGIN_FAILURE));
  },
  logout({ commit }) {
    return auth
      .logout()
      .then(() => commit(LOGOUT))
      .finally(() => commit(REMOVE_TOKEN));
  },
  initialize({ commit }) {
    const token = localStorage.getItem(TOKEN_STORAGE_KEY);

    if (token) {
      commit(SET_TOKEN, token);
    } else {
      commit(REMOVE_TOKEN);
    }
  }
};

const mutations = {
  [LOGIN_BEGIN](state) {
    state.authenticating = true;
    state.error = false;
  },
  [LOGIN_FAILURE](state) {
    state.authenticating = false;
    state.error = true;
  },
  [LOGIN_SUCCESS](state) {
    state.authenticating = false;
    state.error = false;
  },
  [LOGOUT](state) {
    state.authenticating = false;
    state.error = false;
  },
  [SET_TOKEN](state, token) {
    localStorage.setItem(TOKEN_STORAGE_KEY, token);
    session.defaults.headers.Authorization = `Token ${token}`;
    state.token = token;
  },
  [REMOVE_TOKEN](state) {
    localStorage.removeItem(TOKEN_STORAGE_KEY);
    delete session.defaults.headers.Authorization;
    state.token = null;
  }
};

export default {
  namespaced: true,
  state: initialState,
  getters,
  actions,
  mutations
};

src/views/Login.vue

<template>
  <div>
    <form class="login" @submit.prevent="login">
      <h1>Sign in</h1>
      <label>Username</label>
      <input required v-model="Username" type="text" placeholder="Name" />
      <label>Password</label>
      <input
        required
        v-model="Password"
        type="password"
        placeholder="Password"
      />
      <hr />
      <button type="submit">Login</button>
    </form>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      Username: "",
      Password: ""
    };
  },
  methods: {
    /*login() {
      let Username = this.Username;
      let Password = this.Password;
      this.$store
        .dispatch("auth/login", { Username, Password })
        .then(() => this.$router.push("/"))
        .catch(err => console.log(err));*/
    login({ Username, Password }) {
      const API_URL = "http://127.0.0.1:8000";
      const url = `${API_URL}/auth/login/`;
      return axios
        .post(url, { Username, Password })
        .then(() => this.$router.push("/"))
        .catch(err => console.log(err));
    }
  },
  mounted() {
    this.login();
  }
};
</script>

首先,我尝试使用身份验证服务,但失败的原因是OPTIONS而不是POST. 然后我直接使用axios来发布用户并获取令牌,但是失败是不允许的方法,我不知道隐藏的过程是什么,您能解释一下吗?

first, I tried using the auth service but the failure was OPTIONS not POST. then i used axios directly to post user and get token, but then the failure was method not allowed, I do not know what is the hidden process, can you explain please?

<template>
  <div id="app">
    <navbar v-if="isAuthenticated"></navbar>
    <router-view></router-view>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import Navbar from "./components/Navbar";

export default {
  name: "app",
  components: {
    Navbar
  },
  computed: mapGetters("auth", ["isAuthenticated"])
};
</script>

router.js

import Vue from "vue";
import Router from "vue-router";
import About from "./views/About";
import Home from "./views/Home";
import Login from "./views/Login";
import Lost from "./views/Lost";
import PasswordReset from "./views/PasswordReset";
import PasswordResetConfirm from "./views/PasswordResetConfirm";
import Register from "./views/Register";
import VerifyEmail from "./views/VerifyEmail";

import store from "./store/index";

const requireAuthenticated = (to, from, next) => {
  store.dispatch("auth/initialize").then(() => {
    if (!store.getters["auth/isAuthenticated"]) {
      next("/login");
    } else {
      next();
    }
  });
};

const requireUnauthenticated = (to, from, next) => {
  store.dispatch("auth/initialize").then(() => {
    if (store.getters["auth/isAuthenticated"]) {
      next("/home");
    } else {
      next();
    }
  });
};

const redirectLogout = (to, from, next) => {
  store.dispatch("auth/logout").then(() => next("/login"));
};

Vue.use(Router);

export default new Router({
  saveScrollPosition: true,
  routes: [
    {
      path: "/",
      redirect: "/home"
    },
    {
      path: "/about",
      component: About,
      beforeEnter: requireAuthenticated
    },
    {
      path: "/home",
      component: Home,
      beforeEnter: requireAuthenticated
    },
    {
      path: "/password_reset",
      component: PasswordReset
    },
    {
      path: "/password_reset/:uid/:token",
      component: PasswordResetConfirm
    },
    {
      path: "/register",
      component: Register
    },
    {
      path: "/register/:key",
      component: VerifyEmail
    },
    {
      path: "/login",
      component: Login,
      beforeEnter: requireUnauthenticated
    },
    {
      path: "/logout",
      beforeEnter: redirectLogout
    },
    {
      path: "*",
      component: Lost
    }
  ]
});

main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store/index";
import axios from "axios";
import Axios from "axios";
import VueAxios from "vue-axios";
import Vuex from "vuex";

Vue.use(Vuex);
Vue.use(VueAxios, axios);
//Vue.config.productionTip = false;
Vue.prototype.$http = Axios;
const token = localStorage.getItem("token");
if (token) {
  Vue.prototype.$http.defaults.headers.common["Authorization"] = token;
}

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

参考:

https://www.techiediaries.com/vue-axios-tutorial/
https://scotch.io/tutorials/handling-authentication-in-vue-using-vuex
https://github.com/jakemcdermott/vue-django-rest-auth

推荐答案

虽然我的代码看起来有点丑陋,因为我混合了一堆存储库,但至少我使它成功完成了POST.我用

while it seems my code is little ugly because I mixed bunch of repositories, but at least I made it make POST successfully. I used

npm install qs

然后将其导入,然后:

var username = payload.credential.username;
var password = payload.credential.password;

然后编辑

axios.post(url, qs.stringify({ username, password })

它奏效了.

这篇关于无法使用django rest auth配置axios登录并获取auth令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆