基于Cookie的身份验证不适用于离子/角度应用程序

时间:2017-06-21 06:46:24

标签: angular authentication cookies ionic-framework

我正在尝试使用Ionic框架将现有网站转换为混合应用程序。登录时,服务器会发送会话cookie供我用于其他呼叫,但cookie不会保存在浏览器上,导致访问尝试时登录重定向。我在登录提交时使用以下功能。

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let url = 'http://localhost/api/auth/login';

var data = 'username=' + this.credentials.username + '&password=' + 
            this.credentials.password + '&captchaResponse=';

this.http.post(url, data, {headers: headers})
.subscribe(data => {
    if(data.json().result == 'success'){
        this.navCtrl.setRoot(FaultsPage);
    } else {
        alert('Wrong username or password');
    }       
}, err => {
    console.error('Error: ', err);
    alert('Something went wrong, try again later');
});

服务器接受凭据并发送会话cookie。在服务器端将Access-Control-Allow-Credentials设置为true。

我还尝试手动设置cookie,但是我无法访问Set-Cookie标头。

我的Ionic版本是3.4.0并使用Angular 4.2.2。

1 个答案:

答案 0 :(得分:0)

发现问题所在。因为源URL和目标URL都是localhost,浏览器认为它正在生成自己的cookie,而忽略端口号。为了解决这个问题,我将目标网址的域名从localhost更改为计算机的用户名。此外,登录请求还需要将withCredentials设置为true。

相关问题