Angular 8登录未正确设置cookie

时间:2019-12-11 14:17:35

标签: angular authentication xmlhttprequest jwt angular-httpclient

这是一个用Angular 8 FrontEnd和Express.js(Node.js)BackEnd编写的登录系统。

我的目标是通过将登录详细信息发布到/api/login来登录,以检查用户的登录信息,并获得一个带有cookie集(格式为键名access_token和内容{ {1}})以获取进一步的授权,并且还可以重定向到仪表板。如果成功登录,则Bearer <jwt token here>会以/api/login状态码进行响应,并使用带有响应的200提及的cookie-set标头(也称为新cookie)。

我的问题是,使用以下代码会出现此错误,并且没有重定向和cookie:

httpOnly:true

我的代码如下:

Http failure during parsing for http://localhost:3000/api/login"

不建议使用P.S LocalStorage,并将cookie用于身份验证和授权。


如果我添加responseType:'text',则会出现以下错误:

login(username: string, password: string) {
        return this.http.post<any>(`${environment.apiUrl}/api/login`, { username, password })
            .pipe(map(user => {
                // login successful if there's a jwt token in the response
                if (user && user.token) {

                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    // https://dev.to/rdegges/please-stop-using-local-storage-1i04
                    localStorage.setItem('currentUserToken', JSON.stringify(user));
                    this.currentUserSubject.next(user);
                }
                console.log('User:', user);
                return user;
            }));
    }

我的后端代码:

No overload matches this call.
  Overload 1 of 15, '(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<...>', gave the following error.
    Type '"text"' is not assignable to type '"json"'.
  Overload 2 of 15, '(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<...>', gave the following error.
    Type '"text"' is not assignable to type '"json"'.
  Overload 3 of 15, '(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<...>', gave the following error.
    Type '"text"' is not assignable to type '"json"'.

我的新代码包含由于某种原因而无法使用的redir:

app.post('/api/login', apiLimiter, async function (req, res){
  // TODO: implement cookie check whether a still valid token is set and if so respond with cookie already set
  try  {
    let [sorted,users] = await getSorted();
    const pw = req.body.password;
    const hashedPassword = await bcrypt.hash(req.body.password, 10);
    console.log(await bcrypt.compare('testtest',hashedPassword));
    // const user = { id: req.body.id, username: req.body.username, password: req.body.password };
    var user = new User({firstname: req.body.firstname, eMail: req.body.eMail, password: hashedPassword });
    sorted.forEach(async ([firstname, password]) => {
      let result = bcrypt.compareSync(pw, password);
        // r = true if hash = hashed pw
        if (result === true) {
          jwt2.sign({user}, 'secrethere', { expiresIn: '15min'}, (err, token) =>{
            res.cookie(
              'access_token', 'Bearer '+ token, {
                expires: new Date(Date.now() + 900000), // cookie will be removed after 15 mins
                httpOnly: true
              })
            .send(200)
              .redirect(
                'http://localhost:4200/avior/dashboard'
              );
          });
          zehgreatresult = 1;
        } else{
          zehgreatresult = 0;
        }

    });    
  } catch (err) {
    res.status(500).send()
    console.log(err);
  }
  if (zehgreatresult === 0){
    res.send("Wrong password!");
  }
});

2 个答案:

答案 0 :(得分:0)

它应该是处理请求的其他方式。您应该将withCredentials: true用作此类http方法的参数

http.get(someUrl, {withCredentials: true});
http.post(someUrl, body, {withCredentials: true});

使用此选项,它1:将设置您的cookie,2:将您现有的cookie附加到请求中

答案 1 :(得分:0)

默认情况下,Http服务正在等待JSON数据,但是您的API正在发送另一种形式,也许是简单的文本,因此您有两种解决方案:  -尝试更改您的API代码以在PHP中发送编码的JSON数据,例如,我们在.Net JsonConvert.SerializeObject函数中使用json_encode函数...  -如果您无权访问APi,请尝试通过添加以下选项来强制HTTP服务获取文本数据:

this.http.post(
    `${environment.apiUrl}/api/login`,
    { username, password },
    {responseType: 'text'})