Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / Office / Office-Automation

MVC Attribute for License Verification of Office Apps

5.00/5 (4 votes)
25 Dec 2015CPOL 9.6K  
License Verification Attribute for MVC and Office-Addins

Introduction

If you want to add your Office Add-In to Microsoft´s store, you need to make sure to handle the license tokens correctly. For this purpose, this trick shows you how to write a small attribute to handle verification requests.

Background

There are 2 articles from Microsoft you should read about token handling:

Using the Code

Using the Attribute is quite easy. Just mark a controller or action with it and you're done:

C#
[OfficeAuthorizeAttribute(AllowTrialUsers = true)]
public ActionResult Index(string id)
{
 return View();
}

Each call to that action is then checked against the Microsoft Verification Service.

If you want to, you can allow testing that app by setting "AllowTrialUsers".

The Code

C#
public class OfficeAuthorizeAttribute : AuthorizeAttribute
  {
   public bool AllowTrialUsers { get; set; }
   
   protected override bool AuthorizeCore(HttpContextBase httpContext) { 
   var isValid = false;
   if (httpContext.Request["et"] == null) return false; 
   string token = httpContext.Request.Params["et"]; 
   byte[] decodedBytes = Convert.FromBase64String(token); 
   string decodedToken = Encoding.Unicode.GetString(decodedBytes); 


   var service = new VerificationServiceClient(); 
   var result = service.VerifyEntitlementTokenAsync(new VerifyEntitlementTokenRequest() 
               {EntitlementToken = decodedToken}).Result; 

   // Check if license is generally valid 
   if (result.IsValid) {
          if (result.EntitlementType == "Trial" && AllowTrialUsers) isValid = true; 
          if (result.IsExpired) isValid = false; 
          if (result.IsEntitlementExpired) isValid= false; } 
          if (!isValid) { httpContext.Response.Redirect("/home/NotLicensed", true); } 
        else { return true; } return isValid; 
} }

History

  • 23.12.2015 * Created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)