2016-11-18 3 views
0

저는 Angular 2 (JS의 큰 전문가는 아님)와 Rails 4.2 사이의 통합을 작성하고 있습니다. 레일 측면에서 나는 인증을 위해 장치를 사용하고있다. 문제는 사용자 로그인을 요청할 때 응답으로 Set-Cookie 헤더가 반환됩니다. 그러나 어떤 인증 요구 리소스를 요청하려고 할 때 Cookie 헤더의 값은 "Set-Cookie=null"입니다 (값은 Set-Cookie과 같습니까?). 여기에 당신이 일을 끝낼 방법은 다음과 같습니다각도 2 쿠키 인증

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 }); 요청에 적절한 쿠키를 포함해야합니다.

추가 정보가 필요한 경우 의견을 적어주십시오.

답변

1

질문이 꽤 오래되었지만 어쨌든 도움이 되었기를 바랍니다. 나는 그 문제에 대해서도 비틀 거리며 당신의 질문에 대한 답변을 찾고 싶습니다. 이제 그 일을 돌 봅니다.

session.service.ts의 POST 요청에 withCredentials 옵션을 잊어 버린 것 같습니다.

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

이제 쿠키가 브라우저와 저장해야합니다 자격 증명 (이메일과 비밀번호)로 요청을 전송하고 응답이 쿠키를 설정하는 기대, 당신은에 대한 HTTP 서비스를 말해야한다 다음 통계 요청에 올바른 쿠키가 포함되어야합니다.

이 방법이 효과가 있습니까?

건배,
프리드리히