First, see my previous question/answer to leverage FormsAuth Tickets in Owin: OWIN Self-Host CookieAuthentication & Legacy .NET 4.0 Application / FormsAuthenticationTicket
Once you have the ability to decrypt/encrypt your FormsAuth cookie, you can leverage that in IdentityServer.
Since your hosting is most likely different than mine, use this as a reference:
/
-> our main api appBuilder
/auth
-> our identityServer
Our main API appBuilder uses the cookie auth middleware as described in the associated SO post (link) above.
IdenityServer app composition root:
appBuilder.Map("/auth", idsrvApp =>
{
idsrvApp.Use((context, task) =>
{
// since we can authenticate using "Cookies" auth,
// we must add the principal to the env so we can reuse it in the UserService
// oddly, the Context.Authentication.User will clear by the time it gets there and we can't rely on it
// my best guess is because IdentityServer is not authenticated (no cookie set)
if (context.Authentication.User != null && context.Authentication.User.Identity.IsAuthenticated)
context.Environment.Add("auth.principal", context.Authentication.User);
return task.Invoke();
});
idsrvApp.UseIdentityServer(isOptions);
});
UserService.cs
public async Task PreAuthenticateAsync(PreAuthenticationContext context)
{
// if we already have an authenticated user/principal then bypass local authentication
if (_Context.Authentication.User.Identity.IsAuthenticated ||
_Context.Environment.ContainsKey("auth.principal"))
{
var principal = _Context.Authentication.User.Identity.IsAuthenticated
? _Context.Authentication.User
: (ClaimsPrincipal)_Context.Environment["auth.principal"];
context.AuthenticateResult =
new AuthenticateResult(); // set AuthenticateResult
return;
}
}
Please Note:
- Use this as an example.
- Enabling cookie auth on your app or api MAY unsuspectingly compromise your security to CSRF attacks. Ensure you're aware of this attack vector and take the necessary steps to reduce this risk.