如何存储RESTful API的身份验证数据

问题描述

我正在开发使用RESTful API的Angular应用程序。验证是通过基本的HTTP授权标头完成的。

存储与每个请求一起发送的凭据的最佳实践是什么?由于它是RESTful-无状态的,因此没有cookie或令牌。除了本地存储,我看不到任何解决方案,并且我不喜欢它,因为它可能会因JS注入而被盗。

解决方法

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

  1. 加密您的回复
  2. 将其存储在localStorage中
  3. 如果要使用localStorage解密值
,

有一个cookie! 这是通过安全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',data: {
      user
    }
  })
}

在那之后,您只需要为一个来源设置cors选项,并且凭据必须为true。 连接必须通过https协议。如果一切正常,cookie将自动存储。打开控制台,然后在“存储”下的“应用程序”中找到Cookie,然后检查是否有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应用程序中重新加载时,我们都会调用此函数。