Use*_*Man 3 authentication setcookie angular angular5
我正在处理Angular 5中的HttpClient,问题是服务器在登录过程中发送的cookie,似乎Angular忽略了它,因为下一个带有"withCredentials"的请求没有设置它.
我的package.json
...."@ angular/cli":"1.6.3","@ angular/compiler-cli":"^ 5.0.0","@ angular/language-service":"^ 5.0.0",. ...
我的代码
makeLogin (us:string, password:string): Observable<any> {
let body : any = new HttpParams()
.set('username', us)
.set('password', password);
return this.http.post(this.urlLogin,
body.toString(),
{
headers: new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
}
);
}
Run Code Online (Sandbox Code Playgroud)
服务器使用这些标头返回http 200
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:4200
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:17
Date:Tue, 23 Jan 2018 21:05:46 GMT
Expires:0
Pragma:no-cache
Set-Cookie:JSESSIONID=BF9392ED5DE99710B44845201DD26B3F;path=/;HttpOnly
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
Run Code Online (Sandbox Code Playgroud)
之后,下一个请求例如
getEventt (): Observable<any> {
return this.http.get('http://localhost:8080/list',{ withCredentials: true });
}
Run Code Online (Sandbox Code Playgroud)
使用chrome或firefox开发人员工具我看不到发送的cookie,但是如果我使用浏览器或邮递员一切正常,我可以看到cookie已经发送.
我不知道我做错了什么,或者是否以错误的方式使用httpClient.
如果有帮助,服务器部署在tomcat 8上,Angular应用程序在nodejs上运行(npm start)
最后,我能够使它工作!
解决方案是在请求后,
也许我错了,但似乎在Angular 5.0.0中不推荐使用RequestOptions类,所以经过几次尝试点击正确的配置后,这里修复了方法
/** POST: add a new hero to the server */
makeLogin (us:string, password:string): Observable<any> {
let enco : any = new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded');
let body : any = new HttpParams()
.set('username', us)
.set('password', password);
return this.http.post(this.urlServicioLogin,
body.toString(),
{
headers: enco,withCredentials:true
}
);
}
Run Code Online (Sandbox Code Playgroud)
现在使用withCredentials,我可以在浏览器中看到正在设置的cookie,然后在随后的请求中发送它.
注意:如果应用程序必须使用其中使用cookie进行身份验证的休息服务,则所有与后端的交互都需要将withCredentials标志设置为true.
| 归档时间: |
|
| 查看次数: |
14048 次 |
| 最近记录: |