簡體   English   中英

CSRF 令牌和 Nuxt-auth

[英]CSRF token and Nuxt-auth

我現在正在嘗試使用nuxt-auth編寫登錄功能。

我有一個 FastAPI 服務器,它設置為與 HTTPOnly cookies 一起使用,因此它需要一個 csrf 令牌來將用戶扔給我的客戶端。 我無法處理令牌,因為它是 HTTPOnly 所以沒有 LocalStorage

登錄工作正常,但我無法獲得存儲的用戶。 我在向我的/login端點發出請求后,Nuxt 還請求/me端點上的用戶。 但是我收到了 401 響應

缺少 cookie access_token_cookie

/me上的錯誤。 我不知道如何處理它。

我的登錄請求方法

async userLogin() {
  await this.$auth.loginWith('cookie', {
    data: `grant_type=&username=${this.emailInput}&password=${this.passwordInput}&scope=&client_id=&client_secret=&`,
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  })
  await this.$router.push('/account')
}

我讀到 nuxt-auth 不擅長 cookie 模式,但該帖子來自 2018 年,我們現在有一個“cookie”策略。 那么有沒有更好的手動處理身份驗證的解決方法?

我在nuxt.config.js中的auth密鑰

auth: {
  strategies: {
    cookie: {
      endpoints: {
        login: {
          url: "/api/v1/login/login",
          method: "post",
          withCredentials: true
        },
        logout: { url: "/api/v1/login/logout", method: "post" },
        user: {
          url: "/api/v1/users/me",
          method: "get"
        }
      },
      tokenType: "bearer"
    }
  }
}

我在 Nuxt + Django 上有一個基於 http-only cookie 的工作。

我的 Nuxt 應用程序反向代理 API 請求到后端。 因此,它可以在服務器端讀取 cookies。

所以,我創建了auth-ssr.ts中間件來檢查用戶是否登錄

import { Context, Middleware } from '@nuxt/types'
import { parse as parseCookie } from 'cookie' // this is lib https://github.com/jshttp/cookie

/**
 * This middleware is needed when running with SSR
 * it checks if the token in cookie is set and injects it into the nuxtjs/auth module
 * otherwise it will redirect to login
 * @param context
 */
const authMiddleware: Middleware = async (context: Context) => {
  if (process.server && context.req.headers.cookie != null) {
    const cookies = parseCookie(context.req.headers.cookie)
    const token = cookies['session'] || '' // here your cookie name
    if (token) {
      context.$auth.$state.loggedIn = true
    }
  }
}

export default authMiddleware

這里是我的nuxt.config.js

  auth: {
    strategies: {
      cookie: {
        user: {
          property: 'user',
        },
        endpoints: {
          login: {
            url: '/api/v2/auth/login/',
            method: 'post',
          },
          user: {
            url: '/api/v2/auth/user/',  
            method: 'get',
          },
          logout: {
            url: '/api/v2/auth/logout/',
            method: 'post',
          },
        },
      },
    },
    redirect: {
      login: '/login',
    },
    plugins: ['@plugins/axios.ts'],
  },
  
  router: {
    middleware: ['auth-ssr', 'auth'],
  },
  
  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {
    proxy: true,
  },

  proxy: {
    '/api': {
      target: 'https://backend.com/',
    },
  },
  
  ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM