Skip to content

Instantly share code, notes, and snippets.

@ahwm
Last active September 30, 2021 14:06
Show Gist options
  • Save ahwm/9f23a4088fbf8eac45550fc6e09de02d to your computer and use it in GitHub Desktop.
Save ahwm/9f23a4088fbf8eac45550fc6e09de02d to your computer and use it in GitHub Desktop.
Custom Password Checker for Umbraco 9
// if using as standalone package, add package reference to Umbraco.Cms.Web.Common (9.0+)
// We use this to authenticate against a rotating password, which keeps access to employees
// If an employee leaves or it's suspected to be compromised it can be rotated at will
using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Security;
public class PasswordChecker : IBackOfficeUserPasswordChecker
{
static bool Login(string password)
{
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
var data = new { password };
HttpWebRequest req = WebRequest.CreateHttp("url/to/webservice/or/api");
req.Method = "POST";
req.ContentType = "application/json";
var jsondata = JsonConvert.SerializeObject(data);
byte[] reqData = System.Text.Encoding.UTF8.GetBytes(jsondata);
req.ContentLength = reqData.Length;
using (var stream = req.GetRequestStream())
stream.Write(reqData, 0, reqData.Length);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
string r;
using (var str = new StreamReader(resp.GetResponseStream()))
{
r = str.ReadToEnd();
}
var obj = JsonConvert.DeserializeObject<dynamic>(r);
return obj.d;
}
catch
{
return false;
}
}
public Task<BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
{
if (user.Email == "userto@authenticate.com")
{
return Login(password)
? Task.FromResult(BackOfficeUserPasswordCheckerResult.ValidCredentials)
: Task.FromResult(BackOfficeUserPasswordCheckerResult.InvalidCredentials);
}
else
{
return Task.FromResult(BackOfficeUserPasswordCheckerResult.FallbackToDefaultChecker);
}
}
}
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Security;
using Umbraco.Extensions;
public class PasswordComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.AddUnique<IBackOfficeUserPasswordChecker, PasswordChecker>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment