using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Text; using System.Web; using Telligent.Evolution.Extensibility.Rest.Version1; namespace Samples { public class APIKeyRestHost : Telligent.Evolution.Extensibility.Rest.Version1.RestHost { private string _communityUrl = null; private string _adminAPIKey = null; private string _adminUserName = null; public APIKeyRestHost(string communityUrl, string adminUserName, string adminApiKey) { _communityUrl = communityUrl; _adminAPIKey = adminApiKey; _adminUserName = adminUserName; } public override void ApplyAuthenticationToHostRequest(System.Net.HttpWebRequest request, bool forAccessingUser) { var adminKey = String.Format("{0}:{1}", _adminAPIKey, _adminUserName); var adminKeyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(adminKey)); request.Headers.Add("Rest-User-Token", adminKeyBase64); if (forAccessingUser) { var httpContext = this.GetCurrentHttpContext(); if (!httpContext.User.Identity.IsAuthenticated) throw new AuthenticationException("This REST Host does not support anonymous access."); var username = httpContext.User.Identity.Name; var user = this.GetToDynamic(2, "users/{username}.json", false, new RestGetOptions() { PathParameters = { { "username", username } } }); if (user == null) throw new ApplicationException(string.Format("User '{0}' wasn't found. Create this user in your community first")); //NOTE: You could attempt to auto create the account using the admin API key, this host chooses not to. //Apply impersonation request.Headers.Add("Rest-Impersonate-User", username); } } public override string EvolutionRootUrl { get { return _communityUrl; } } public override string Name { get { return "APIKeyRestHost"; } } } }