【问题标题】:Why does the csrf check not work on the server?为什么 csrf 检查在服务器上不起作用?
【发布时间】:2022-01-29 20:43:33
【问题描述】:
const csrfProtection = csrf({
  cookie: {httpOnly: true}
})


// Middleware
app.use(express.json())
app.use(cookieParser())
app.use(csrfProtection)
app.use(cors({
  origin: 'http://localhost:8081',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  exposedHeaders: 'XSRF-TOKEN'
}))
app.use(helmet.frameguard({ action: 'SAMEORIGIN' }))
app.use(helmet.ieNoOpen())
app.use(helmet.hidePoweredBy())
app.use(safetyMiddleware)

app.use('/api', router)
app.use(errorMiddleware)

我做了一个路由,每次访问该站点时,它都会在请求标头中发送一个令牌

router.get('/', (req, res) => {
  const xsrf = req.csrfToken()
  res.set("XSRF-Token", xsrf).json('true')
})

客户端 axios: 示例:

const $host = axios.create({
  withCredentials: true,
  baseURL: process.env.VUE_APP_SERVER_URL,
  headers: {
    "xsrf_token": localStorage.getItem('csrf')
  }
})

export const csrfAuth = async () => {
  const {headers} = await $host.get('/')
  localStorage.setItem('csrf', headers['xsrf-token'])
  return headers
}

export const loginPassword = async (email, password) => {
  const {data} = await $host.post('/user/login', {email, password})
  return data
}

第一个请求进来并在 cookie 中保存一个令牌,第二个在本地存储中。

第一个问题是,它们应该不同吗? 为什么服务器以 500 状态响应登录请求?该过程甚至没有到达下一个中间件

谢谢。

【问题讨论】:

    标签: node.js express csrf


    【解决方案1】:

    声明

    localStorage.getItem('csrf')
    

    仅在浏览器读取客户端javascript时执行一次,即之前调用csrfAuth()并声明

    localStorage.setItem('csrf', headers['xsrf-token'])
    

    执行。因此,在发出 POST /user/login 请求时,$host 中的 xsrf-token 标头没有所需的值。

    【讨论】:

    • 工作!我检查正确吗?还是我需要以某种方式验证标头?
    猜你喜欢
    • 2019-05-22
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2016-02-18
    • 1970-01-01
    相关资源
    最近更新 更多