I have a .NET Core Identity API that is not the direct internet facing API.
The Yarp API is the one accessible from the Internet and I want to use the Identity cookie to know if user is logged in and if not redirect him to login page.
I stored in DB the Identity API DataProtection keys to be accessible by all Identity instances:
services.AddDataProtection().PersistKeysToDbContext<ApplicationDbContext>();
All works fine I can see the key in the DataProtectionKey
table in the Identity DB.
Now I want in the Yarp API to have a middleware that check the Identity cookie .AspNetCore.Identity.Application
if it is present and if it is ok to know if otherwise I should challenge the request to redirect towards login in Identity (login path is allowed by the middleware).
In the Yarp api I configured the same line towards same db and the authentication with cookie:
services.AddDataProtection().PersistKeysToDbContext<ApplicationDbContext>();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie();
In the middleware I attempted both the:
var authResult = await context.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
and the:
TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtector);
AuthenticationTicket ticket = ticketDataFormat.Unprotect(cookieContent);
//I can see in the cookieContent the encrypted string
but none of them are successful.
Any idea what else I should do ?
Indeed RuikaiFeng suggestion was correct:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
}).AddCookie(IdentityConstants.ApplicationScheme);
but there was also something else: the SetApplicationName that need to be the same value in both apis:
services.AddDataProtection().PersistKeysToDbContext<ApplicationDbContext>()
.SetApplicationName("SameApiName");
And now the httpContext will show the needed information directly:
context?.User?.Identity?.IsAuthenticated