I have an ASP.NET application that I’m transitioning from the old Membership system to Identity framework (with a view to eventually port the whole thing to .NET Core, but that’s a long way off).
I also have another .NET framework console application (it actually runs as a Windows service, but that’s neither here nor there) that basically does some offline processing of jobs that it pulls off a queue in a database table and signals back to the ASP.NET app via Signal R.
Sometimes, the console app uses Selenium to render something in the ASP.NET app and take a screenshot of it. Sometimes when it does that, it is important that the chrome driver instance running via Selenium is logged in.
Now, since the console app doesn’t have the user’s password, it can’t log in via the usual API login function that requires a username and a password. So with the old membership system, I just had the console write an auth cookie that would match the one that the ASP.NET app would write. This required making sure that the system.web
section of the console app’s app.config
matched the ASP.NET app’s web.config
, so same machinekey
and most importantly the same compatibilityMode
(which tripped me up for a long time).
I had both the ASP.NET and the console app calling this shared code:
public static HttpCookie CreateAuthenticationTicket(IUserModel user, bool persist)
{
if (user == null)
{
throw new InvalidOperationException("Cannot write authentication cookie - no user");
}
string userData = Newtonsoft.Json.JsonConvert.SerializeObject(user);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, user.Email, DateTime.Now, persist ? DateTime.Now.AddMonths(6) : DateTime.Now.AddHours(1), persist, userData); // 1 Yr if "remember me", 1 hour if not.
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie c = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
if (persist)
{
c.Expires = ticket.Expiration;
}
if (!string.IsNullOrEmpty(FormsAuthentication.CookieDomain))
{
c.Domain = FormsAuthentication.CookieDomain;
}
return c;
}
And then in the console app, before calling whatever Javascript method I need via Selenium, I set the cookie in Selenium. This all worked fine.
But I’m not sure how to pull off the same when using Identity. I’m not sure where the cookie is getting written and what it’s using for encoding. Basically, I need to be able to write an Identity compatible cookie in the console app.
As an alternative, the ASP.NET app also allows using Bearer tokens, but I’m not having much luck figuring out how to get both apps to write compatible tokens either.
This is the setup on the ASP.NET side:
public void ConfigureOAuth(IAppBuilder app, System.Web.Mvc.IDependencyResolver kernel)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider(kernel.GetService<UserManager<IUserModel, int>>()),
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
var bearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(bearerOptions);
app.CreatePerOwinContext<CeaApplicationUserManager>((option, context) =>
{
return kernel.GetService<CeaApplicationUserManager>();
});
app.CreatePerOwinContext<CEASignInManager>((option, context) =>
{
return kernel.GetService<CEASignInManager> ();
});
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = PathString.Empty,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<CeaApplicationUserManager, IUserModel, int>(
TimeSpan.FromMinutes(30),
(manager, user) => manager.GenerateUserIdentityAsync(user),
(claim) => claim.GetUserId<int>())
},
CookieDomain = FormsAuthentication.CookieDomain,
CookiePath = "/; sameSite=None; secure"
});
}
On the ASP.NET side, I can do something like this to manually produce a token:
var token = oAuthOptions.AccessTokenFormat.Protect(ticket);
Where oAuthOptions
is the same OAuthBearerAuthenticationOptions
that was used in the start up (which is just a new OAuthBearerAuthenticationOptions
). If I try the same in the console app, the OAuthBearerAuthenticationOptions.AccessTokenFormat
is null.
Clearly somewhere in creating and registering the SimpleAuthorizationServerProvider
, it must get assigned, but I don’t know where and I don’t know how to give my console app a suitable instance. Or what application/machine settings it is using to encrypt the bearer token.
Any suggestions, or other approaches, are welcome.