Welcome Guest! To enable all features, please Login or Register.

Notification

Icon
Error

Options
View
Last Go to last post Unread Go to first unread post
#1 Posted : Tuesday, January 8, 2019 4:01:21 PM(UTC)
Anthony Northrup

Groups: Registered, Tech Support, Administrators
Posts: 199

Was thanked: 28 time(s) in 28 post(s)

If you're using the DocumentViewer within your company's application, you may wish to add HTTP authorization for downloading internal documents. Below are the few steps you'll need to get started.

Step 1: Provide the header within the client
Our JavaScript SDK allows the developer to customize the requests made to the Documents Service in any way they'd like. You'll simply need to hook into the DocumentFactory.prepareAjax event. Below are the code snippets from the full sample project, which showcases how to add the basic authorization header:
Code:

// Setup the prepareAjax event
lt.Document.DocumentFactory.prepareAjax.add(prepareAjaxCallback);

// Callback definition
function prepareAjaxCallback(sender, args) {
   // Only modify the loadFromUri method
   if (args.sourceClass.toLowerCase() != "documentfactory" ||
         args.sourceMethod.toLowerCase() != "loadfromuri")
      return;
   
   // Ensure the headers object exists
   if (!args.settings.headers)
      args.settings.headers = {};
   
   // Add the authorization header
   var myUsername = "username";
   var myPassword = "password";
   args.settings.headers["Authorization"] = "Basic " + btoa(myUsername + ":" + myPassword);
}

Note: A request made by the DocumentViewer for loading an image does not fire this event by default. To fire the prepareAjax event for requests made to the service, simply set the DocumentViewer.useAjaxImageLoading property to true.

Below is a download link for the complete client-side demo for this:
File Attachment(s):
CustomHeaders.zip (355kb) downloaded 77 time(s).
Step 2: Pass-through the header within the Documents Service
By default, our Documents Service uses a blank WebClient for the LoadFromUri requests. However, you can provide a custom one by modifying the LoadDocumentOptions object used within the FactoryController.cs file:

Project Location: LEADTOOLS 20\Examples\JS\Documents\DocumentViewer\Services\DocumentsService
File Location: Controllers\FactoryController.cs
Line Number: 101 - 105
Code:

var loadOptions = new LoadDocumentOptions();
loadOptions.Cache = cache;
loadOptions.UseCache = cache != null;
loadOptions.CachePolicy = ServiceHelper.CreatePolicy();

// EDIT: Updated WebClient
loadOptions.WebClient = new WebClient();
// Pass-through various headers
string[] passthroughHeaders = new string[] { "Authorization" };
foreach (string header in passthroughHeaders)
   if (Request.Headers.Contains(header))
      if (Request.Headers.TryGetValues(header, out IEnumerable<string> values))
         foreach (string value in values)
            loadOptions.WebClient.Headers.Add(header, value);
      else
         loadOptions.WebClient.Headers.Add(header);

As you can see from the passthroughHeaders variable in the snippet above, this can be easily extended to pass any header you'd like.

Optional step 3: Testing the authorization header
By default, this authorization header is not required. Below is the modification I made to the Documents Service for testing purposes.

Project Location: LEADTOOLS 20\Examples\JS\Documents\DocumentViewer\Services\DocumentsService
File Location: Controllers\TestController.cs
Line Number: 28
Code:

// EDIT: Added test endpoint
[HttpGet]
public HttpResponseMessage AuthorizedImage()
{
   // Configure expected username/password
   string expectedUsername = "username";
   string expectedPassword = "password";

   // Validate authentication header
   HttpResponseMessage response = new HttpResponseMessage
   {
      Content = new StringContent("Unknown error"),
      StatusCode = HttpStatusCode.InternalServerError
   };
   try
   {
      // Ensure header is present
      var authHeader = Request.Headers.Authorization;
      if (authHeader == null)
         throw new NullReferenceException("No authorization header present");

      // Validate scheme
      if (!authHeader.Scheme.Equals("basic", StringComparison.CurrentCultureIgnoreCase))
         throw new ArgumentException("Not using basic authorization");

      // Validate parameter
      string decoded = System.Text.Encoding.Default.GetString(
         Convert.FromBase64String(authHeader.Parameter)
      );
      var match = new System.Text.RegularExpressions.Regex("^([^:]*):(.*)$").Match(decoded);
      if (match == null || !match.Success)
         throw new ArgumentException("Parameter not formatted properly");

      // Validate some username and password
      if (!match.Groups[1].Value.Equals(expectedUsername))
         throw new ArgumentException("Invalid username");
      if (!match.Groups[2].Value.Equals(expectedPassword))
         throw new ArgumentException("Invalid password");
   }
   catch (Exception ex)
   {
      response.Content = new StringContent(
         $"Authorization header not configured properly: {ex.Message}"
      );
      response.StatusCode = HttpStatusCode.Unauthorized;
      return response;
   }

   // Validated successfully
   response.StatusCode = HttpStatusCode.OK;

   // Populate with data
   response.Content = new ByteArrayContent(
      System.IO.File.ReadAllBytes(@"C:\Users\Public\Documents\LEADTOOLS Images\cannon.jpg")
   );

   return response;
}
Anthony Northrup
Developer Support Engineer
LEAD Technologies, Inc.

LEAD Logo
 

Try the latest version of LEADTOOLS for free for 60 days by downloading the evaluation: https://www.leadtools.com/downloads

Wanna join the discussion? Login to your LEADTOOLS Support accountor Register a new forum account.

You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Powered by YAF.NET | YAF.NET © 2003-2024, Yet Another Forum.NET
This page was generated in 0.066 seconds.