2016-11-18 143 views
0

我正在编写Angular 2(不是JS中的大专家)和Rails 4.2之间的一些集成。在Rails方面,我使用设计进行身份验证。事情是当我要求登录用户时,Set-Cookie标题返回响应。但是,然后,当我试图请求任何验证所需的资源Cookie标头的值为"Set-Cookie=null"(如没有值Set-Cookie?)。下面是它是如何做:Angular 2 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

你的问题是相当古老的,但我希望它无论如何帮助。我也偶然发现了这个问题,并希望找到你的问题。现在我处理这件事。

我想你忘记了session.service.ts的POST请求中的withCredentials选项。当您发送带有凭据(电子邮件和密码)的请求,你期待的回应设置cookie,你应该告诉该HTTP服务:

return this.http.post(
    this.createSessionUrl, 
    JSON.stringify({user:{email: email, password: password}}), 
    { headers: this.headers, withCredentials: true } 
) 

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

这是行不通的?

干杯,
Friedrich