Simeon Grigorovich
Simeon Grigorovich

Reputation: 581

nativescript authenticating at backend web api

I am new to mobile development. My project is build using asp.net. For authentication I am using build it UserManager & User.Identity.

I have bunch of existing web apis and I wish to use them from mobile app. I know , I could pass a secret hash to web api after authenticating, but that would involve a huge code refactoring.

I been wondering if there other ways to handle authentication & authorization with nativescript & asp.net .

Do you know any useful resources for this topic?

Many thanks for your help!

Upvotes: 1

Views: 2307

Answers (1)

George Edwards
George Edwards

Reputation: 9229

It depends quite heavily on your API structure, but I would recommend somethign like this:

Firstly you would need to use the Nativescript Http module. An implementation to get a an HTTP GET calls returned header might look like this:

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

So your backend might return a JSON Web Token as a header. In which case on the success callback you would probably want to store your token in the applications persistent memory. I would use the Application Settings module, which would look something like:

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

Then before you make an API call for a new token you can check if there is a stored value:

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

Then with your token, you would want to make an API call, e.g. this POST and add the token as a header:

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

Your backend would need to check the Auth header and validate the JWT to decide whether to accept or reject the call.

Alternatively, there some nice plugins for various Backends-as-a-Service, e.g. Azure and Firebase

Upvotes: 9

Related Questions