首页 > 解决方案 > 如何在 NativeScript 应用程序中恢复 Express Session Authentication 的会话 ID?

问题描述

系好安全带,这个有点复杂。我知道 Express 会向浏览器发送一个connect.sidcookie ...... Passport 使用它来反序列化 Web 请求中的用户。不仅如此,当我从我的 NativeScript 应用程序(我在 Windows PC 上的 Pixel 2 模拟器上运行,但我知道它也适用于 iOS)登录到我的应用程序时,cookie 似乎已正确设置和发送以及未来的网络请求。我也了解application-settingsAPI 的工作原理,并且您可以使用它来存储用户识别令牌以供将来启动应用程序(这样我就不必每次都登录)。

所以这就是断开连接的地方。可以想象,如果我存储了请求标头中的 cookie,我可以覆盖它,但是我在任何地方都找不到有关如何从 nativescript 中的成功登录请求中检索 cookie 的文档。

这是代码:

令牌服务

import { Injectable }     from "@angular/core";
import { getString, setString } from "application-settings";

export class TokenSvc {
   static isLoggedIn(): boolean {
      return !!getString("token");
   }

   static get token(): string {
      return getString("token");
   }

   static set token(token: string) {
      setString("token", token);
   }
}

登录组件

(请注意,我在尝试从新的 HttpHeaders 实例中获取 cookie 时令人尴尬……不知道为什么我认为这会起作用。)

@Component({
    selector: "app-login",
    moduleId: module.id,
    templateUrl: "./login.component.html",
    styleUrls: ["./login.component.scss"]
})
export class LoginComponent {
    credentials: ILoginCredentials;
    @ViewChild("password") password: ElementRef;
    @ViewChild("handle") handle: ElementRef;
    @ViewChild("confirmPassword") confirmPassword: ElementRef;

    constructor(private page: Page, private router: Router, private AuthSvc: AuthSvc, private _store: Store<AppStore>) {
        this.page.actionBarHidden = true;
        this.credentials = {
           email: "",
           password: "",
           cPassword: "",
           handle: "",
           publicName: ""
        };
    }


    login() {
        const loginCredentials: ICredentials = {
            username: this.credentials.email,
            password: this.credentials.password,
            rememberMe: false
        };
        this.AuthSvc.login(loginCredentials).subscribe(
            (payload) => {
                console.log(payload);
                if (payload.failure) {
                    alert(payload.failure);
                } else {
                    // user!
                    let cookies = new HttpHeaders().get("Cookie");
                    console.log(cookies);
                    TokenSvc.token = cookies;
                    this._store.dispatch({ type: "SET_USER", payload: payload });
                    this.router.navigate(["/tabs"]);
                }
            }, () => alert("Unfortunately we were unable to create your account.")
      );
   }

}

这里的基本问题是......如何在 NativeScript 应用程序设置中使用 Node/Express 后端保持基于 cookie 的会话?

标签: cookiesnativescript

解决方案


基本答案是:你没有。

在移动开发方面,首选 JWT、OAuth2 或任何其他基于令牌的身份验证方法。您也可以对 Web 使用相同的身份验证方法。

使用安全存储存储用户令牌,并将令牌与用户发出的任何请求一起发送。


推荐阅读