简体   繁体   English

如何做高效的客户端认证?

[英]How to do efficient client-side authentication?

For my web app, which has both a public/not logged in view as well as an admin view, I have been using a completely separated frontend (React served with nginx) and backend. 对于同时具有公共/未登录视图和管理员视图的Web应用程序,我一直在使用完全独立的前端(React与nginx一起提供)和后端。 One of the appeals of separating the two is that if I wanted I could totally rewrite the backend in Go or Rust and not affect the frontend at all. 将两者分开的吸引力之一是,如果我愿意,我可以完全用Go或Rust重写后端,而完全不影响前端。

However, to do client side authentication I essentially have to maintain two different “states”: one on the client, one on the server. 但是,要进行客户端身份验证,我基本上必须维护两个不同的“状态”:一个在客户端,一个在服务器上。

Since client side authentication is risky/not secure, I wrap all my authenicated components/routes on the frontend in an authorization HOC which makes an HTTP call to the server to see if the user is authorized. 由于客户端身份验证存在风险/不安全,因此我将所有经过身份验证的组件/路由包装在前端的授权HOC中,该HOC对服务器进行HTTP调用以查看用户是否被授权。 This is more secure but in production noticeably slow, delaying each route render for almost 2 seconds. 这是更安全的方法,但在生产中会明显变慢,从而使每个路径渲染延迟了将近2秒钟。

The alternative is to be less secure, just maintain authentication on the client side without HTTP calls (ie setting isAuth to true in redux). 替代方案是降低安全性,仅在客户端进行身份验证而不进行HTTP调用(即在redux isAuth设置为true)。 This means users can bypass protected routes, but can't do too much damage as the server uses authentication middleware. 这意味着用户可以绕过受保护的路由,但是由于服务器使用身份验证中间件,因此不会造成太大的损害。

Any advice, experience, or opinions here? 这里有什么建议,经验或意见吗? Should I just go isomorphic and couple myself to full-stack Javascript? 我应该只是同构并耦合到全栈Javascript吗?

You should be generating a session cookie or an auth token on your server when the user logs in. It should have some sort of lifespan so that it isn't good forever. 当用户登录时,您应该在服务器上生成会话cookie或auth令牌。它应具有某种寿命,以至于不能永远使用。 Then you should store the auth token on the client and use it as an authentication header in future requests. 然后,您应该将auth令牌存储在客户端上,并在将来的请求中将其用作身份验证标头。 Your api should require an authtoken as a header in all future requests and check to make sure that auth token is still valid. 您的api应该在以后的所有请求中都要求authtoken作为标头,并检查以确保auth令牌仍然有效。 If valid return the regular response if not return a 40x session timeout error. 如果有效,则返回常规响应;如果不返回,则返回40x会话超时错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM