I was unable to solve the original request of instantiating the OWIN context but worked around it by decrypting the cookie directly which gives me access to the user identity and claims. Using this information I am then able to log the user into SharePoint using FBA.
The code I used to decrypt the cookie follows. The first step is to override the creation of the OWIN auth cookie in your website that does the original authentication. This is so you can control things like the cookie name, encryption keys and data protection strings. Note app is an IAppBuilder
from the OWIN pipeline.
IDataProtector dataProtector = app.CreateDataProtector("Your purposes", "v1");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
...
CookieName = ".yourCookieName",
TicketDataFormat = new TicketDataFormat(dataProtector)
});
Next I created a method in my SharePoint custom login aspx page that could decrypt the auth cookie. In order for this to work the machineKey settings in the web.config need to match between your SharePoint web server and login application web server.
private AuthenticationTicket GetAuthTicket()
{
HttpCookie authCookie = Request.Cookies[".yourCookieName"];
if (authCookie == null) return null;
IDataProtector dataProtector = new MachineKeyDataProtector(new [] {"Your purposes", "v1"});
var ticketDataFormat = new TicketDataFormat(dataProtector);
AuthenticationTicket ticket = ticketDataFormat.Unprotect(authCookie.Value);
return ticket;
}
The final part is the custom MachineKeyDataProtector
class. This just uses the default MachineKey classes in System.Web.Security to protect and unprotect the cookie data (this class uses the machineKey settings which is why they need to match across servers).
public class MachineKeyDataProtector : IDataProtector
{
private readonly string[] _purposes;
public MachineKeyDataProtector(params string[] purposes)
{
_purposes = purposes;
}
public virtual byte[] Protect(byte[] userData)
{
return MachineKey.Protect(userData, _purposes);
}
public virtual byte[] Unprotect(byte[] protectedData)
{
return MachineKey.Unprotect(protectedData, _purposes);
}
}
I hope this is useful to someone else and if you do figure out how to use OWIN inside a SharePoint site then please let me know.