65.9K
CodeProject is changing. Read more.
Home

MVC Attribute for License Verification of Office Apps

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Dec 24, 2015

CPOL
viewsIcon

9611

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:

    [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

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