Angular 2 cookie身份验证

时间:2016-11-18 08:35:39

标签: ruby-on-rails angular cookies

我正在编写Angular 2(不是JS的大专家)和Rails 4.2之间的一些集成。在Rails方面,我正在使用设计进行身份验证。问题是,当我请求登录用户时,会返回Set-Cookie标头作为响应。但是,当我尝试请求任何身份验证所需的资源时,Cookie标头的值为"Set-Cookie=null"(就像没有Set-Cookie的值一样?)。以下是它的完成方式:

session.service.ts

@Injectable()
export class SessionService{
    private headers = new Headers({'Content-Type': 'application/json', 'Accept': 'application/json'})
    private createSessionUrl = 'http://localhost:3002/users/sign_in';

    constructor(
        private http: Http
    ) { }

    create(email: string, password: string): Promise<User>{
        return this.http.post(this.createSessionUrl, JSON.stringify({user:{email: email, password: password}}),
            { headers: this.headers })
            .toPromise()
            .then(response => response.json() as User)
            .catch(this.handleError)
    }

    private handleError(error: any): Promise<any> {
        return Promise.reject(error.message || error);
    }
}

statistics.service.ts

import { Injectable }       from '@angular/core';
import { Headers, Http, RequestOptions }    from '@angular/http';
import { Statistics }       from '../models/statistics.models'

import 'rxjs/add/operator/toPromise';

@Injectable()
export class StatisticsService{
    private headers = new Headers({'Content-Type': 'application/json', 'Accept': 'application/json'})
    private statisticsUrl = 'http://localhost:3002/statistics';

    constructor(
        private http: Http
    ) {}

    show(): Promise<Statistics>{
        let options = new RequestOptions({ headers: this.headers, withCredentials: true });
        return this.http.get(this.statisticsUrl, options)
            .toPromise()
            .then(response => response.json() as Statistics)
            .catch(this.handleError)
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

据我所知,let options = new RequestOptions({ headers: this.headers, withCredentials: true }); 应该在请求中包含适当的Cookie。

如果需要任何额外信息,请写下评论。

1 个答案:

答案 0 :(得分:2)

你的问题很老了,但我希望无论如何都有帮助。我也偶然发现了这个问题,并希望找到你的问题。现在我照顾好了。

我想您忘记了Linux System Programming, 2nd Edition的POST请求中的withCredentials选项。当您发送带有凭据(电子邮件和密码)的请求并且您希望响应设置cookie时,您应该告诉http服务:

session.service.ts

现在,cookie应该由浏览器存储,下一个统计信息请求应该包含正确的cookie。

这有用吗?

干杯,
弗里德里希