【问题标题】:Cookie Based Authentication Not Working On Ionic/Angular App基于 Cookie 的身份验证在 Ionic/Angular 应用程序上不起作用
【发布时间】:2017-11-23 22:02:18
【问题描述】:

我正在尝试使用 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。

【问题讨论】:

  • 编辑:URL 位于本地主机上,因为该网站的服务器不支持 CORS,并且我已在服务器的本地副本上实现了 CORS 功能。

标签: angular authentication cookies ionic-framework


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-09-06
    • 2011-04-12
    • 2018-06-30
    • 2020-06-20
    • 2019-11-20
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多