CSharp · Mvc
using System;
using System.ComponentModel.DataAnnotations;
namespace HelloWorldMvcApp
{
public class SampleViewModel
{
public string Question
{
get;
set;
}
//See here for list of answers
public string Answer
{
get;
set;
}
}
}
@model HelloWorldMvcApp.SampleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello</h1>
<label>Authentication Header</label>
<input class="form-control" disabled data-val="true" id="Question" value="">
<br/>
<button class="btn btn-primary submit">Try Me</button>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
$(function(){
var answer = '@Model.Answer';
$('.submit').click(function(){
$.ajax({
url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {Question: ''},
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
$('#Question').val('Tuned-HMAC ' + resp);
}});
});
});
</script>
</body>
</html>
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new SampleViewModel());
}
[HttpPost]
public JsonResult GetAnswer(string question)
{
// Pre-generated access/secret keys. TG to provide to every client.
var accessKey = "3LzpnTzxItLdONtnZf5h";
var secretKey = "9zYU17hx5UsRJAJnzwx62bbqFhdqDyBy";
// Api to call to retrieve asset infomation
var endpoint = "https://api-delivery-connect.tunedglobal.com/api/v4/assets/122256677/stream?quality=High";
//STEP 1: Generate nonce and timestamp
// Nonce
string nonce = Guid.NewGuid().ToString("N");
// Timestamp using unix time
DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = DateTime.UtcNow - epochStart;
string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();
// STEP 2: Encode request url using UTF8 encoding
//Note: Ensure the encoded string is all in lowercase.
var uri = System.Web.HttpUtility.UrlEncode(endpoint, Encoding.UTF8);
//Note: Skip to step 6 for http GET requests or requests where there is no Payload to be sent with the request
// STEP 3: Serialize Json object / payload
// Sample Json object / payload
var data = new SampleRequestPayload { Id = 1, Name = "Joe Bloggs"} ;
//Serialize to string
string serializedData = JsonConvert.SerializeObject(data);
// STEP 4: Convert serialized payload to bytes using UTF8 encoding table
byte[] content = Encoding.UTF8.GetBytes(serializedData);
// Initialize authentication code
var authCode = string.Empty;
// STEP 5: Hash the request body using MD5 hashing algorithm
MD5 md5 = MD5.Create();
byte[] requestContentHash = md5.ComputeHash(content);
// Convert hashed data to base 64 string
string requestContentBase64String = Convert.ToBase64String(requestContentHash);
// STEP 6: Create Raw signature string. Format: {your-access-key}{http-method}{request-url}{request-body-base64-string}{nonce}{timestamp}
string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", accessKey, "PUT", uri, requestContentBase64String, nonce, requestTimeStamp);
// STEP 7: Convert formatted signature raw string to bytes
byte[] signature = Encoding.UTF8.GetBytes(signatureRawData);
// STEP 8: Coverty secret key to byte array
var secretKeyByteArray = Convert.FromBase64String(secretKey);
//STEP 9: Create HMAC for signature string using secret key byte array
using (HMACSHA256 sha = new HMACSHA256(secretKeyByteArray))
{
// Sign the request
byte[] signatureBytes = sha.ComputeHash(signature);
// STEP 10: Convert the signatureBytes result to base64 string
string requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
//STEP 11: Generate authentication code. Format: {your-access-key}:{signature}:{nonce}:{timestamp}
//This is the file signature string that needs to be sent in Tuned-HMAC auth header
authCode = string.Format("{0}:{1}:{2}:{3}", accessKey, requestSignatureBase64String, nonce, requestTimeStamp);
}
return Json(authCode);
}
}
public class SampleRequestPayload
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
}