void OnBeginRequest(object sender, System.EventArgs e) { try { bool oauthValidationEnabled = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsOauthValidationEnabled"]); if (oauthValidationEnabled) { //Exclude WebApi requests from this validation if (HttpContext.Current.Request.Url.AbsolutePath.StartsWith("/api") == false) { if (HttpContext.Current.Request.Headers["authorization"] != null) { try { string authHeader = HttpContext.Current.Request.Headers["authorization"]; //string authString = HttpContext.Current.Request.Headers["authorization"]; string userId = HttpContext.Current.Request.Headers["x-jive-user-id"]; if (authHeader.StartsWith(JIVE_EXTN) == false || authHeader.Contains(PARAM_SIGNATURE) == false) { Trace.WriteLine("Authorization header not formatted correctly"); throw new HttpRequestValidationException(); } Dictionary <string, string> parameterDict = GetParametersFromAuthHeader(authHeader); string signature = parameterDict[PARAM_SIGNATURE]; parameterDict.Remove(PARAM_SIGNATURE); string algorithm = parameterDict[PARAM_ALGORITHM]; string clientId = parameterDict[PARAM_CLIENT_ID]; string jiveUrl = parameterDict[PARAM_JIVE_URL]; string tenantId = parameterDict[PARAM_TENANT_ID]; string timeStampStr = parameterDict[PARAM_TIMESTAMP]; long timestampMilliSeconds = Convert.ToInt64(timeStampStr); DateTime timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestampMilliSeconds); if (timestamp > DateTime.Now.AddMinutes(5) || DateTime.Now.AddMinutes(-5) > timestamp) { Trace.WriteLine("Timestamp older than 5 minutes"); int timestampDiff = timestamp.CompareTo(DateTime.Now); throw new HttpRequestValidationException("Timestamp difference more than 5 minutes. Difference: " + timestampDiff.ToString()); } var _myAddon = db.JiveAddons .Include("JiveInstance") .Where(a => a.JiveInstance.JiveInstanceId.Equals(tenantId)); if (_myAddon.Count() == 0) { Trace.WriteLine("Jive Instance not found"); throw new HttpRequestValidationException(); } JiveAddon myAddon = _myAddon.Single(); if (myAddon.ClientId.Equals(clientId) == false) { Trace.WriteLine("Not the expected client id for this tenant"); throw new HttpRequestValidationException(); } string parameterStrWithoutSignature = authHeader.Substring(JIVE_EXTN.Length, authHeader.IndexOf(PARAM_SIGNATURE) - (PARAM_SIGNATURE.Length + 1)); string expectedSignature = validateSignature(parameterStrWithoutSignature, myAddon.ClientSecret); if (expectedSignature.Equals(signature)) { string ownerId = userId + "@" + tenantId; GenericIdentity MyIdentity = new GenericIdentity(ownerId); String[] MyStringArray = { "User" }; GenericPrincipal MyPrincipal = new GenericPrincipal(MyIdentity, MyStringArray); Thread.CurrentPrincipal = MyPrincipal; } else { Trace.WriteLine("Signature not correctly validated"); throw new HttpRequestValidationException(); } } catch (HttpRequestValidationException authEx) { Trace.WriteLine(authEx.Message, "Error"); HttpContext.Current.Response.Status = "401 Unauthorized"; HttpContext.Current.Response.StatusCode = 401; HttpContext.Current.Response.End(); } } else { if (HttpContext.Current.Request.Url.AbsolutePath.Contains(".") == false) { HttpContext.Current.Response.Status = "403 Forbidden"; HttpContext.Current.Response.StatusCode = 403; HttpContext.Current.Response.End(); } } } } } catch (Exception ex) { Trace.WriteLine(ex, "Error"); } }
public override void OnActionExecuting(HttpActionContext actionContext) { try { //Example for retrieving config settings from the web config //bool oauthValidationEnabled = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsOauthValidationEnabled"]); bool oauthValidationEnabled = true; string uri = actionContext.Request.RequestUri.AbsolutePath; string host = actionContext.Request.RequestUri.Host; if (oauthValidationEnabled) { if (actionContext.Request.Headers.Authorization != null) { try { var authTemp = actionContext.Request.Headers.Authorization; string authHeader = authTemp.ToString(); string userId = "0"; if (HttpContext.Current.Request.Headers["x-jive-user-id"] != null) { userId = HttpContext.Current.Request.Headers["x-jive-user-id"]; } if (authHeader.StartsWith(JIVE_EXTN) == false || authHeader.Contains(PARAM_SIGNATURE) == false) { Trace.WriteLine("Authorization header not formatted correctly"); throw new HttpRequestValidationException("Authorization header not formatted correctly"); } Dictionary <string, string> parameterDict = GetParametersFromAuthHeader(authHeader); string signature = parameterDict[PARAM_SIGNATURE]; parameterDict.Remove(PARAM_SIGNATURE); string algorithm = parameterDict[PARAM_ALGORITHM]; string clientId = parameterDict[PARAM_CLIENT_ID]; string jiveUrl = parameterDict[PARAM_JIVE_URL]; string tenantId = parameterDict[PARAM_TENANT_ID]; string timeStampStr = parameterDict[PARAM_TIMESTAMP]; long timestampMilliSeconds = Convert.ToInt64(timeStampStr); DateTime timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestampMilliSeconds); if (timestamp > DateTime.Now.AddMinutes(5) || DateTime.Now.AddMinutes(-5) > timestamp) { Trace.WriteLine("Timestamp older than 5 minutes"); int timestampDiff = timestamp.CompareTo(DateTime.Now); throw new HttpRequestValidationException("Timestamp difference more than 5 minutes. Difference: " + timestampDiff.ToString()); } var _myAddon = db.JiveAddons .Include("JiveInstance") .Where(a => a.JiveInstance.JiveInstanceId.Equals(tenantId)); if (_myAddon.Count() == 0) { Trace.WriteLine("Jive Instance not found"); throw new HttpRequestValidationException(); } JiveAddon myAddon = _myAddon.Single(); if (myAddon.ClientId.Equals(clientId) == false) { Trace.WriteLine("Not the expected client id for this tenant"); throw new HttpRequestValidationException("Not the expected client id for this tenant"); } string parameterStrWithoutSignature = authHeader.Substring(JIVE_EXTN.Length, authHeader.IndexOf(PARAM_SIGNATURE) - (PARAM_SIGNATURE.Length + 1)); string expectedSignature = validateSignature(parameterStrWithoutSignature, myAddon.ClientSecret); if (expectedSignature.Equals(signature)) { string ownerId = userId + "@" + tenantId; GenericIdentity MyIdentity = new GenericIdentity(ownerId); String[] MyStringArray = { "User" }; GenericPrincipal MyPrincipal = new GenericPrincipal(MyIdentity, MyStringArray); Thread.CurrentPrincipal = MyPrincipal; } else { Trace.WriteLine("Signature not correctly validated"); throw new HttpRequestValidationException("Signature not correctly validated"); } } catch (HttpRequestValidationException authEx) { Trace.WriteLine(authEx.Message, "Error"); //NewRelic.Api.Agent.NewRelic.NoticeError(authEx); actionContext.Response = new System.Net.Http.HttpResponseMessage(); actionContext.Response.Content = null; actionContext.Response.StatusCode = HttpStatusCode.Unauthorized; } } } else { if (actionContext.Request.Headers.Authorization != null) { var authTemp = actionContext.Request.Headers.Authorization; string authString = authTemp.Parameter; //string authString = HttpContext.Current.Request.Headers["authorization"]; string userId = HttpContext.Current.Request.Headers["x-jive-user-id"]; string[] authStringArray = authString.Split('&'); string tenantId = null; string jiveUrl = null; foreach (string authElement in authStringArray) { string[] keyValue = authElement.Split('='); if (keyValue[0].Equals("tenant_id")) { tenantId = keyValue[1]; } if (keyValue[0].Equals("jive_url")) { jiveUrl = HttpUtility.UrlDecode(keyValue[1]); } } string ownerId = userId + "@" + tenantId; GenericIdentity MyIdentity = new GenericIdentity(ownerId); String[] MyStringArray = { "User" }; GenericPrincipal MyPrincipal = new GenericPrincipal(MyIdentity, MyStringArray); Thread.CurrentPrincipal = MyPrincipal; } else { throw new HttpRequestValidationException("Authorization header not formatted correctly"); } } } catch (Exception ex) { //NewRelic.Api.Agent.NewRelic.NoticeError(ex); actionContext.Response = new System.Net.Http.HttpResponseMessage(); actionContext.Response.Content = null; actionContext.Response.StatusCode = HttpStatusCode.InternalServerError; } }
public async Task <HttpResponseMessage> RegisterJiveInstance(JiveAddonRegistrationDto jiveRegistration) { if (ModelState.IsValid) { try { _response = await Request.Content.ReadAsStringAsync(); //Convert our Jive Addon registration from the Data Transfer Object into an internal object //Example of an add-on registration request //{ // "tenantId": "b22e3911-28ef-480c-ae3b-ca791ba86952", // "jiveSignatureURL": "https://market.apps.jivesoftware.com/appsmarket/services/rest/jive/instance/validation/8ce5c231-fab8-46b1-b8b2-fc65ascesb5d", // "timestamp": "2014-02-17T14:07:09.135+0000", // "jiveUrl": "https://sandbox.jiveon.com", // "jiveSignature": "r3gMujBUIWLUyvAp81TK9YasdAdDaRtlsQ6x+Ig=", // "clientSecret": "bmdoprg381uypaffd7xrl123c9znb5fjsb.s", // "clientId": "mrymd1f8oziyamo0yxdasdw9yovigd9t.i" //} Mapper.CreateMap <JiveAddonRegistrationDto, JiveAddonRegistration>(); JiveAddonRegistration myJiveRegistration = Mapper.Map <JiveAddonRegistrationDto, JiveAddonRegistration>(jiveRegistration); db.JiveRegistrations.Add(myJiveRegistration); db.SaveChanges(); if (Convert.ToBoolean(jiveRegistration.uninstalled) != true) { //check if this is a valid Jive environment StringBuilder validationPayload = new StringBuilder(); validationPayload.Append("clientId:"); validationPayload.Append(myJiveRegistration.ClientId + "\n"); validationPayload.Append("clientSecret:"); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] secret = encoding.GetBytes(myJiveRegistration.ClientSecret); HMACSHA256 hmacsha256 = new HMACSHA256(); hmacsha256.ComputeHash(secret); foreach (byte b in hmacsha256.Hash) { validationPayload.AppendFormat("{0:x2}", b); } validationPayload.Append("\n" + "jiveSignatureURL:"); validationPayload.Append(myJiveRegistration.JiveSignatureURL + "\n"); validationPayload.Append("jiveUrl:"); validationPayload.Append(myJiveRegistration.JiveUrl + "\n"); validationPayload.Append("tenantId:"); validationPayload.Append(myJiveRegistration.TenantId + "\n"); validationPayload.Append("timestamp:"); validationPayload.Append(myJiveRegistration.Timestamp + "\n"); string validationPayloadString = validationPayload.ToString(); byte[] binaryPayload = encoding.GetBytes(validationPayloadString); //Validate with the Jive webservice that the request orininated from JIve //Alternatively validate with your local environment in some form //This method is not fully implemented in this example using (WebClient wc = new WebClient()) { wc.Headers.Set("X-Jive-MAC", myJiveRegistration.JiveSignature); try { byte[] postResult = wc.UploadData(myJiveRegistration.JiveSignatureURL, binaryPayload); } catch (System.Net.WebException webEx) { Trace.WriteLine(webEx, "Error"); } } } //Check if the Jive instance already exists, otherwise create it JiveInstance myJiveInstance = db.JiveInstances.Find(myJiveRegistration.TenantId); if (myJiveInstance == null) { //Jive instance not created yet. Let's build it myJiveInstance = new JiveInstance(); myJiveInstance.DateCreated = DateTime.Now; myJiveInstance.IsComplete = false; myJiveInstance.JiveInstanceId = myJiveRegistration.TenantId; myJiveInstance.LastUpdated = DateTime.Now; myJiveInstance.Url = myJiveRegistration.JiveUrl; myJiveInstance.IsComplete = false; myJiveInstance.IsLicensed = true; myJiveInstance.IsInstalledViaAddon = true; db.JiveInstances.Add(myJiveInstance); db.SaveChanges(); User newAdmin = new User(); newAdmin.DateCreated = DateTime.Now; } JiveAddon myJiveAddon; if (Convert.ToBoolean(myJiveRegistration.Uninstalled) == true) { //Addon uninstalled myJiveAddon = db.JiveAddons .Include("JiveInstance") .Where(a => a.JiveInstance.JiveInstanceId.Equals(myJiveRegistration.TenantId)).First(); myJiveAddon.Uninstalled = true; db.SaveChanges(); } else { //Addon is being installed //Create a new add-on var _jiveAddons = db.JiveAddons .Include("JiveInstance") .Where(a => a.JiveInstance.JiveInstanceId.Equals(myJiveRegistration.TenantId)); if (_jiveAddons.Count() == 0) { myJiveAddon = new JiveAddon(); myJiveAddon.AddonType = "My wonderful app"; myJiveAddon.ClientId = myJiveRegistration.ClientId; string clientSecret = myJiveRegistration.ClientSecret; if (clientSecret.EndsWith(".s")) { clientSecret = clientSecret.TrimEnd('s'); clientSecret = clientSecret.TrimEnd('.'); } myJiveAddon.ClientSecret = clientSecret; myJiveAddon.DateCreated = DateTime.Now; myJiveAddon.JiveInstance = myJiveInstance; myJiveAddon.Code = myJiveRegistration.Code; myJiveAddon.Scope = myJiveRegistration.Scope; myJiveRegistration.Timestamp = myJiveRegistration.Timestamp; myJiveAddon.Uninstalled = false; db.JiveAddons.Add(myJiveAddon); db.SaveChanges(); } else { //Update existing addon myJiveAddon = _jiveAddons.First(); myJiveAddon.ClientId = myJiveRegistration.ClientId; string clientSecret = myJiveRegistration.ClientSecret; if (clientSecret.EndsWith(".s")) { clientSecret = clientSecret.TrimEnd('s'); clientSecret = clientSecret.TrimEnd('.'); } myJiveAddon.ClientSecret = clientSecret; myJiveAddon.Code = myJiveRegistration.Code; myJiveAddon.Scope = myJiveRegistration.Scope; myJiveRegistration.Timestamp = myJiveRegistration.Timestamp; myJiveAddon.Uninstalled = false; db.SaveChanges(); } } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, jiveRegistration); return(response); } catch (Exception ex) { Trace.WriteLine(ex, "Error"); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError); return(response); } } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } }