Use TOTP for securing API Requests

Did you know that if APIs are left unprotected, anyone can use them, potentially resulting in numerous calls that can bring down the API (DoS/DDoS Attack) or even update the data without the user’s consent?

Let’s look at this from the perspective of a curious developer. Sometimes, I only want to trace the network request in the browser by launching the Dev Tools (commonly by pressing the F12 key) and looking at the Network Tab.

In the past, WebApps were directly linked with Sessions. Based on whether a session is valid, the request would go through. If no request is performed in a given time frame, it would simply exhaust the session in 20 minutes (default in some servers unless configured). Now, we build WebApps purely on the client side, allowing them to consume Rest-based APIs. Our services are strictly API-first because it will enable us to scale them quickly and efficiently. Modern WebApps are built using frameworks like ReactJS, NextJS, Angular, and VueJS, resulting in single-page applications (SPA) that are purely client-side.

Let’s look at this technically: HTTP is a Stateless Protocol. This means the server doesn’t need to remember anything between requests when using HTTP. It just receives a URL and some headers and sends back data.

We use attributes like [Authorize] in our Asp.Net Core-based Web APIs to authorize them securely. This involves generating JWT (JSON Web Tokens) and sending them along with the Login Response to be stored on the Client Side. Any future requests include the JWT Token, which gets automatically validated. JWTs are an open, industry-standard RFC 7519 method for representing claims securely between two parties and can be used with various technologies beyond Asp.Net Core, such as Spring.

When you send the JWT back to the server, it’s typically sent using the Header in subsequent requests. The server generally looks for the Authorization Header values, which comprise the keyword Bearer, followed by the JWT Token.

<code>Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFudWJoYXYgUmFuamFuIiwiaWF0IjoxNTE2MjM5MDIyfQ.ALU4G8LdHbt6FCqxtr2hgfJw1RR7nMken2x0SC_hZ3g</code>

The above is an example of the token being sent. You can copy the JWT Token and visit https://jwt.io to check its values.

If I missed something about JWT, feel free to comment.

JWT Decoded

This is one of the reasons why I thought of protecting my APIs. I stumbled upon features like Remember Me when developing a WebApp using Asp.Net Core WebAPI as the backend and ReactJS as the front end. Although a simple feature, Remember Me could be implemented in various ways. Initially, I thought, why complicate things with cookies? I will be building mobile apps for the site anyway! However, it always bugged me that my JWT was stored in LocalStorage. The reason is simple: I can have users for this website ranging from someone who has zero knowledge of how it works to someone like me or, at worst, a potential hacker. A simple attack vector is impersonation if my JWT token is accessed. Any JavaScript can easily access this token stored in Local Storage. Due to this, I thought, yes, we can save the JWT in a Cookie sent from the Server, but it needs properties like HttpOnly, etc. But what if my API is used from a Mobile App? Considering the Cookie, it’s not a norm to extract the said token from a Cookie (although it is doable). Thus, I started looking into TOTP.

Now, let’s explore TOTP (Time-based One-Time Password) and its role in securing API requests. TOTP authenticates users based on a shared secret key and the current time. It generates a unique, short-lived password that changes every 30 seconds.

Have you heard of TOTP before? It’s the same thing when you use your Microsoft Authenticator or Google Authenticator Apps to provide a 6-digit code for Login using 2FA (2-Factor Authentication).

Why Use TOTP for API Security?

While JWTs provide a robust mechanism for user authentication and session management, they are not immune to attacks, especially if the tokens are stored insecurely or intercepted during transmission. TOTP adds an extra layer of security by requiring a time-based token in addition to the JWT. This ensures that even if a JWT is compromised, the attacker still needs the TOTP to authenticate, significantly reducing the risk of unauthorized access.

Implementing TOTP in APIs

Here’s a high-level overview of how to implement TOTP for API requests:

1. Generate a Shared Secret: When a user registers or logs in, generate a TOTP secret key dynamically, hidden from any storage. This key is used to create TOTP tokens.

2. TOTP Token Generation: Use libraries to generate TOTP tokens based on the shared secret and the current time.

3. API Request Validation: On the server side, validate the incoming JWT as usual. Additionally, the TOTP token is required in the request header or body. Validate the TOTP token using the same shared secret and the current time.

<code>// Example code snippet for validating TOTP in Node.js

const speakeasy = require('speakeasy');

// Secret stored on the server
const secret = 'KZXW6YPBOI======';

function validateTOTP(token) {
  const verified = speakeasy.totp.verify({
    secret: secret,
    encoding: 'base32',
    token: token,
  });
  return verified;
}

// On receiving an API request
const tokenFromClient = '123456'; // TOTP token from client
if (validateTOTP(tokenFromClient)) {
  console.log('TOTP token is valid!');
} else {
  console.log('Invalid TOTP token!');
}
</code>

Using TOTP ensures that even if the JWT is compromised, unauthorized access is prevented because the TOTP token, which changes every 30 seconds, is required.

Akavache losing data in Xamarin.iOS

Akavache Logo
Akavache Logo - Image from https://github.com/reactiveui/Akavache

Today I am sharing an issue that I believe many have faced and probably tried resolving a lot. The issue is mostly seen when using Akavache in Xamarin.iOS (even when using Xamarin.Forms). The issue is this:

When using the App either in Simulator or Device, we try to use say Akavache’s BlobCache to store some data. During the runtime of the App, we tend to read the data back from the BlobCache and play with it. However, the real reason we use BlobCache is that we want to store some data like UserInformation, etc. to persist during App restarts.

But we see that the information is lost during the App restarts.

The main reason behind this is the Akavache is built to be used on top of SQLite. However, if the required plugin or rather the NuGet package is not found, the data is then persisted temporarily as the SQLite is not initialized for use with Akavache.

In order to fix this, I installed the NuGet Package SQLitePCLRaw.bundle_e_sqlite3 in all the projects.

The moment it got installed, I could see that my data was getting cached and persisted during the App restarts. I hope it helps.

Do ensure that you are initializing the Application Name:

BlobCache.ApplicationName = "AkavacheExperiment";

Happy Coding!

Page Navigation using Messaging Center

Messaging Center
Messaging Center- Image used from https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center

MessagingCenter doesn’t need any introduction in this world of Xamarin. As the name suggests, it is clearly used for Messages. Now the question arises What Messages? Are these Chats? Who is Sending? Who is Receiving? etc…etc…etc…

Let’s look at the gist of Messaging Center from here:
The publish-subscribe pattern is a messaging pattern in which publishers send messages without having knowledge of any receivers, known as subscribers. Similarly, subscribers listen for specific messages, without having knowledge of any publishers. You can read more about the common explanation here. If you are still not aware of MessagingCenter, then kindly read this Documentation on MessagingCenter.

We know that while using MessagingCenter, there are two actors in the scene, Publisher and Subscriber. Now, what happens is that the Subscriber subscribes for a specific message and performs an action whenever the Publisher publishes the desired message.

Now let’s look at the use case for this:
We always see this question arising wherein the developers are trying to perform operations on Page Navigation from the ViewModel like Navigation.PushAsync, Navigation.PushModalAsync, Navigation.PopAsync or Navigation.PopModalAsync etc. However, we all know that the Navigation property is only accessible as part of the Page.

The sole reason behind using frameworks like MVVM is to isolate the View from ViewModel. Consider the scenario where we have a ListView and in its header is the Add Button. Now, this Add Button is bound to the Add Command in the ViewModel which needs to perform the function call of Navigation.PushModalAsync().

So here when we think about performing operations like PushModalAsync, the challenge is that we cannot just go ahead and use the Navigation object unless we store the Root/Parent page somewhere in another variable, etc.

If you create a New Blank Xamarin.Forms App with Master Page, you will get a templated App with few lines of code.
In your MainPage constructor, you can try this:

public partial class MainPage : MasterDetailPage
{
    Dictionary MenuPages = new Dictionary();
    public MainPage()
    {
        InitializeComponent();
        MasterBehavior = MasterBehavior.Popover;

        //Subscribing to the Message NavTo
        MessagingCenter.Subscribe("AppName", "NavTo", async (sender, arg) =>   
        {
            await NavigateFromMenu(arg);
        });
    }
 
    public async Task NavigateFromMenu(int id)
    {
        if (!MenuPages.ContainsKey(id))
        {
            switch (id)
            {
                case (int)MenuItemType.Home:
                    MenuPages.Add(id, new NavigationPage(new HomePage()));
                    break;
                case (int)MenuItemType.About:
                    MenuPages.Add(id, new NavigationPage(new AboutPage()));
                    break;
                case (int)MenuItemType.Add:
                    MenuPages.Add(id, new NavigationPage(new AddPage()));
                    break;
            }
        }

        var newPage = MenuPages.ContainsKey(id) ? MenuPages[id] : null;
        if (newPage != null && Detail != newPage)
        {
            Detail = newPage;
            IsPresened = false;
        }
    }
} 

Now we can send the Message from our MainViewModel like this:

private void AddCommand(object obj)
{
    MessagingCenter.Send<string, int>("AppName", "NavTo", (int)MenuItemType.Add);
    //MenuItemType is an Enum.
}

In the above example, the AddCommand sends a Message of NavTo with the Add Parameter. The main page which is already subscribed to this will try to Navigate based on the parameters provided.

As shown above, you can easily perform Page Navigation using MessagingCenter.

Happy Coding!!!




MessagingCenter is Everywhere

Messaging Center
Messaging Center- Image used from https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center

Did you know that the concept of MessagingCenter is seen everywhere even in our daily life? Before moving into this, I would recommend reading this Documentation on MessagingCenter.

MessagingCenter primarily consist of Publisher and Subscriber.
Publisher’s job is to keep on publishing messages.
Subscriber’s job is to subscribe to specific messages and perform some action whenever a desired message is published.

Let’s look at this mechanism and how we see it in our daily life…
Think of it in this way, you as a user of Mobile Phones, are always subscribed to the Notifications that are delivered to your device. A notification sound is like a message which triggers you to check your Phone. It’s like your Device is communicating with you through a specific Sound. For example, if the sound is that of your ring-tone you will always check your Phone for Incoming Calls. In this scenario, your Phone is the Publisher and you are the Subscriber.

Not just this, you are given a Name by Birth and whenever even in the crowd you hear your name even though there are people discussing someone else you immediately react to it. It’s like you are inherently Subscribed to your Name and anything followed through as arguments to the action that needs to be performed.

I believe this was just a simple explanation that popped up in my mind while explaining to a friend of mine.

Happy Coding!!!

Building a Phone Dialler for Families and Friends using Xamarin – Part 2

Hello, people, I am back to talk more into the developments of my App. I am trying to name the App as Family Dialler. In case you have any better name, please do reach out or comment below. If any of you are a designer, please do help me with the look and feel of this App.

Family Dialler

Well, the App is now working to some extent in Debugging Mode. I am first working on a skeleton of the App with the minimum designs and layouts. I am doing this to test the functionalities that are required to go further with the App requirements.

NuGet Packages

I am listing some of the NuGet packages that I have come across and using them or am thinking of using in the future (as the App progresses). I have been maintaining a list of these packages and will keep on updating the same in a post published earlier.

I can access the Contacts as we speak and can perform the basic CRUD operations on my favorite contacts. Looking forward to finishing some more things 🙂

Building a Phone Dialler for Families and Friends using Xamarin – Part 1

The idea was to create a Phone Dialler where I can mark my folks (friends and families) as Favorites. You might think that we already have similar functionality available in our current Dialer, so why re-invent the wheel.

However, the way I want to do is that we have a different kind of implementation and that the dialer is something that intrigues me. So let’s see how far I can go into.

Now, in order to achieve this, obviously I will use my favorite IDE i.e., Visual Studio and the technology would be Xamarin.

The Basic Functionality

Let’s try to examine the blocks involved in this kind of App and the basic requirements in order to achieve this. Definitely, we can have other services that can be attached to it at a later point in time but then let’s keep the options to a basic minimum for now.
For the App to work, I would need to access the Phone Contacts as well as Call Logs. The App should have existing Contacts accessed from the Device, Call Logs to access the History, as well as an SQLite DB to maintain the favorites. Let’s not forget the Dialer Pad for dialing numbers directly.

  • Permissions:
    • Access Phone Contacts (Read and Write)
    • Access Call Logs (Read and Write)

To build the UI, we can always make use of ListViews, MasterDetail Pages, etc., to render the desired UI. I will definitely make use of the NuGet packages to get some faster results.

I have already started pushing in my code to GitHub. Once the Code is ready in terms of basic functionality, I will make it public, but for now, let’s hang onto it.

NuGet Packages for Xamarin

Well, since I have been working on lots of Xamarin stuffs, I thought it’s sometimes best to list down the NuGet packages that are really amazing and helps you create the boiler plate of your App in a much easier and faster way.

The NuGet Packages

Let’s look at the worthy NuGet packages which are worth looking into.

NameDescriptionPlatforms
Acr.UserDialogsA cross platform library that allows you to call for standard user dialogs from a shared/portable libraryXamarin.Android Xamarin.iOS UWP Xamarin.Forms
SQLiteNetExtensionsSQLite-Net Extensions is a very simple ORM that provides cascade operations, one-to-one, one-to-many, many-to-one, many-to-many, inverse and text-blobbed relationships on top of the sqlite-net library.Xamarin.Forms
Rg.Plugins.PopupPlugin for Xamarin Forms. Allows you to open any page as a popup. Xamarin.Forms
Xamarin.Forms.DebugRainbows Adds a very colorful debug mode to each of your ContentPages that lets you immediately see where all of your elements are located. Xamarin.Forms
AkavacheAn asynchronous, persistent key-value store for desktop and mobile applications on .NETXamarin.Forms

I will keep updating this list as I keep encountering on these stuffs. Feel free to let me know if there are some I have missed.

Happy Coding!

Fix WKWebView Content Cut Issue

A lot of Devs who have tried integrating UIWebView in the past had the option to fix things like Content getting cut when scrolling to the end.

Generally, when this happens the easiest way is to add padding to the Bottom of the ScrollView. The same can be done by making use of ContentInset. ContentInset is the custom distance that the content view is inset from the safe area or scroll view edges.

Let’s see how to add the same for a CustomRenderer in Xamarin.iOS for Xamarin.Forms:

 webView.ScrollView.ContentInset = new UIEdgeInsets(0, 0, 100f, 0); 

Here in the above line, we add the ContentInset to the ScrollView asking it to accept padding of 100f to the bottom of the ScrollView. You can customize it as per your needs.

Happy Coding!

ContentResolver for Xamarin.Forms

We often face some challenges when working with Xamarin.Forms.
In a similar instance, I faced one when trying to read Contacts. I found myself in a fix because the data that I had received for an Image was basically a URI with type content://

The data retrieved from the Contact for a Thumbnail was something like this:
content://com.android.contacts/contacts/29059/photo

Obviously, Xamarin.Forms is fully equipped to deal with any sort of ImageSource that comes in its ways, except something that is directly a platform specific.

In order to render this, I went ahead with DependencyServices.
Here’s my implementation for this:

IContentImageService.cs
public interface IContentImageService
{
    Stream GetImageUri(string contentUri);
}
ContentResolverMethods.cs
[assembly: Xamarin.Forms.Dependency(typeof(ContentResolverMethods))]
namespace YourNamespace.Droid.Dependencies
{
    public class ContentResolverMethods : IContentImageService
    {
        public Stream GetImageUri(string contentUri)
        {
            var uri = Android.Net.Uri.Parse(contentUri);
            return Android.App.Application.Context.ContentResolver.OpenInputStream(uri);
        }
    }
}

Now in order to use this, you can always invoke the method implemented in Android using DependencyServices from within the Xamarin.Forms Project which is either a .NetStandard, Shared or a PCL based project

var stream = DependencyService.Get<IContentImageService>().GetImageUri(imageUri);
return ImageSource.FromStream(() => stream);

Happy Coding!

Disable Screenshot in App

Many a times we have seen App which detect and won’t allow us to take screenshots. So as an App developer on Xamarin, it’s quiet intriguing to know how to achieve that. Turns out, it’s just a line of code that would allow us to achieve that.

this.Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);

Setting up the Flags for Window Manager does the job. Now just add this in a Blank Android App and test it out. You will see that it works just like that.

Happy Coding!