【问题标题】:How to store auth data for RESTful API如何存储 RESTful API 的身份验证数据
【发布时间】:2021-01-23 04:19:06
【问题描述】:

我正在开发一个使用 RESTful API 的 Angular 应用程序。身份验证使用基本的 HTTP 授权标头完成。

存储要随每个请求发送的凭据的最佳做法是什么?因为它是 RESTful - 无状态的,所以没有 cookie 或令牌。除了本地存储,我没有看到任何解决方案,我不喜欢它,因为它可能会被 JS 注入窃取。

【问题讨论】:

    标签: angular rest authentication restful-authentication


    【解决方案1】:

    您可以将其加密存储在本地存储中:

    1. 加密您的回复
    2. 将其存储在本地存储中
    3. 如果你想使用它,请从 localStorage 中解密值

    【讨论】:

    • 加密密钥必须存储在浏览器中,所以任何攻击者都可以解密凭证,不是吗?
    • 在 API 中加密怎么样?我只是在想一个好的解决方案。
    【解决方案2】:

    有一个饼干! 这是通过安全 cookie 完成的。

    signUp(email: string, password: string, passwordConfirm: string, name: string): Observable<User> {
        const url = `${this.BASE_URL}/users/signup`;
        return this.http.post<User>(url, {email, password, passwordConfirm, name}, {
          withCredentials: true, // this part is very important
        });
      }
    
    //Node js 
    const createAndSendToken = (user, statusCode, req,res) => {
      const token = signToken(user._id, user.name);
      const cookieOptions =  { 
        expires: new Date(
          Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
          ),
          httpOnly: true
      }
    
      // if(process.env.NODE_ENV === 'production') cookieOptions.secure = true;
    
      if(req.secure || req.headers('x-forwarded-proto') === 'https') cookieOptions.secure = true; //this part is for heroku, it's important to have secure option set to true inside cookieOptions
    
      res.cookie('jwt', token, cookieOptions);
      
      user.password = undefined;
    
      res.status(statusCode).json({
        status: 'success',
        token,
        data: {
          user
        }
      })
    }
    

    在此之后,您只为一个来源设置 cors 选项,并且凭据需要为真。 连接必须通过 https 协议。如果一切正常,cookie 将自动存储。打开控制台,然后在 Storage 下打开 Application 你有 Cookies 并检查是否有 cookie。在每个请求中,您都可以访问 Rest Api 中的 cookie

    exports.isLoggedIn = async (req, res, next) => {
      if (req.cookies.jwt) {
        try {
      // 1) Verification token
      const decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET)
      
      // 2) Check if user still exists
      const currentUser = await User.findById(decoded.id);
      
      if(!currentUser) {
        return next();
      }
    
      // 4) Check if user changed password after the token was issued
      if(currentUser.changedPasswordAfter(decoded.iat)) {
        return next()
      }
      //THERE IS A LOGGED IN USER
      req.user = currentUser;
      return next();  
    
      } catch(err) {
    
        return next();
      }   
        
      }
      next();
    }
    

    在每次重新加载 Angular 应用程序时,我们都会调用此函数。

    【讨论】:

      猜你喜欢
      • 2011-11-28
      • 2013-08-21
      • 2014-04-05
      • 2011-10-02
      • 2014-11-15
      • 1970-01-01
      • 2021-02-16
      • 2012-03-14
      • 1970-01-01
      相关资源
      最近更新 更多