nativescript在后端web api进行身份验证

Sim*_*ich 1 asp.net authentication asp.net-mvc nativescript angular

我是移动开发的新手.我的项目是使用asp.net构建的.对于身份验证我正在使用构建它UserManager和User.Identity.

我有一堆现有的网络api,我希望从移动应用程序中使用它们.我知道,我可以在验证后将秘密哈希传递给web api,但这将涉及巨大的代码重构.

我一直想知道是否还有其他方法可以使用nativescript和asp.net处理身份验证和授权.

你知道这个主题的任何有用资源吗?

非常感谢您的帮助!

Geo*_*rds 9

它在很大程度上取决于您的API结构,但我会建议像这样的东西:

首先,您需要使用Nativescript Http模块.获取HTTP GET调用返回标头的实现可能如下所示:

http.request({ url: "https://httpbin.org/get", method: "GET" }).then(function (response) {
    //// Argument (response) is HttpResponse!
    //for (var header in response.headers) {
    //    console.log(header + ":" + response.headers[header]);
    //}
}, function (e) {
    //// Argument (e) is Error!
});
Run Code Online (Sandbox Code Playgroud)

因此,您的后端可能会将JSON Web令牌作为标头返回.在成功回调的情况下,您可能希望将令牌存储在应用程序持久性内存中.我会使用应用程序设置模块,它看起来像:

var appSettings = require("application-settings");
appSettings.setString("storedToken", tokenValue);
Run Code Online (Sandbox Code Playgroud)

然后,在为新令牌进行API调用之前,您可以检查是否存在存储值:

var tokenValue = appSettings.getString("storedToken");
if (tokenValue === undefined { 
    //do API call
}
Run Code Online (Sandbox Code Playgroud)

然后使用您的令牌,您可以进行API调用,例如此POST并将标记添加为标头:

http.request({
    url: "https://httpbin.org/post",
    method: "POST",
    headers: { "Content-Type": "application/json", "Auth": tokenValue },
    content: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
}).then(function (response) {
    // result = response.content.toJSON();
    // console.log(result);
}, function (e) {
    // console.log("Error occurred " + e);
});
Run Code Online (Sandbox Code Playgroud)

您的后端需要检查Auth标头并验证JWT以决定是接受还是拒绝该呼叫.

或者,有一些很好的插件可用于各种Backends-as-a-Service,例如Azure和Firebase