2016-08-02 26 views
1

我是新來的移動開發。我的項目是使用asp.net構建的。對於我使用的身份驗證構建UserManager & User.Identity。nativescript在後端web api驗證

我有一堆現有的網絡API,我希望從移動應用程序中使用它們。 我知道,在進行身份驗證後,我可以將一個祕密散列傳遞給web api,但這會涉及巨大的代碼重構。

我一直想知道是否有其他方式來處理身份驗證&授權與本地腳本& asp.net。

你知道這個話題的有用資源嗎?

非常感謝您的幫助!

+1

您是否使用NativeScript-Angular模塊?如果遵循angular2 Auth主題,那麼這將是一個不錯的入門者,並按George的建議存儲授權密鑰。另外看看GitHub中的例子:https://github.com/NativeScript/nativescript-angular/blob/master/ng-sample/app/examples/router/login-test.ts,特別是如果你使用的是更新的路由器。 – Matthew

+0

我的主要問題是如何保持支持的會話。 Asp.net在登錄後傳回一個auth cookie。我正在嘗試使用@George Edwards對appSetting –

+0

@SimeonGrigorovich保存cookie進行評論,我的方法是無狀態的 - 您不必維護會話(可擴展性更高)。您只需將JWT設置爲具有到期時間/日期,並且任何具有有效jwt的請求都將獲得授權。沒有必要對所有人登錄信息。 –

回答

7

這相當嚴重依賴於你的API結構,但我會建議somethign這樣的:

首先,你需要使用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! 
}); 

所以你的後端可能會返回一個JSON網絡令牌作爲標題。在成功回調的情況下,您可能需要將令牌存儲在應用程序持久內存中。我會用Application Settings模塊,它看起來是這樣的:

var appSettings = require("application-settings"); 
appSettings.setString("storedToken", tokenValue); 

然後你做一個API調用一個新的令牌,你可以檢查前是否有保存價值:

var tokenValue = appSettings.getString("storedToken"); 
if (tokenValue === undefined { 
    //do API call 
} 

然後用你的令牌,你會想要進行API調用,例如這個帖子並添加標記爲一標題:

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); 
}); 

後端需要檢查Auth頭和驗證JWT來決定是否接受或拒絕呼叫。

另外,還有一些不錯的後端即服務插件, Azure和Firebase

+0

謝謝你。在你的幫助下,我發現了一個JWT指南:http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2 / –