Authenticating using ntlm inside a webview in Xamarin

Skriven av

Stefan_Singer

Stefan Singer

We recently started using Xamarin for a client project here at We made you look. We basically wanted to be able to display a mobile web page inside a webview along with some native logic “on the side”.

The Problem

The website is HTTP NTLM Authentication-protected. Normally, when browsing to such a page, the browser will present a login dialog to the user, but not when you are using a webview to display the content.

Furthermore, we wanted to share as much of the logic and UI between iOS and Android, since we’re using Xamarin.

Googling the issue wasn’t all to helpful, almost no one have used even HTTP Basic Authentication within webviews in Xamarin, and even fewer have used NTLM Authentication. We know how to solve this in Android, but doing the same for iOS was trickier.

The solution

We stopped looking for Xamarin based solutions and instead directly looked at objective-C code. By fetching the HTTP 403 response when loading the webview, we know that the user is not logged in. If that’s the case, we display a login dialog and basically set the default HTTP Authentaticon credentials for the app, like so:

var credentialSpace = new NSUrlProtectionSpace("the.domain.com", 80, "http", "the.domain.com", "NTLM");

NSUrlCredentialStorage credentialStorage = NSUrlCredentialStorage.SharedCredentialStorage;
var credential = new NSUrlCredential ("username-from-dialog", "password-from-dialog", NSUrlCredentialPersistence.ForSession);

credentialStorage.SetDefaultCredential (credential, credentialSpace);

And in the end, it was as simple as that. We hope it’ll come to use for someone else too.

Vikten av uppföljning

Jag tror de flesta har sagt detta till antingen kollegor eller kunder: ”Uppföljning är det viktigast...

Föregående inlägg

Visual Studio 2013 installation crashing on Windows 8.1

After doing a clean install of Windows 8.1 on my Macbook Air using Bootcamp (even though Microsoft d...

Nästa inlägg