I have several asp.net Web API microservices and I want to use the so called single sign in operation using Cookie. So when I sign in in my Identity API all other APIs would know who is signed in.
Now – several questions popped when doing so:
I am using this method (and Identity SignInManager method PasswordSignInAsync) :
builder.Services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "Identity.Cookie";
config.LoginPath = "/User/Login";
config.LogoutPath = "/User/Logout";
});
…to log in and produce the cookie.
Now, I searched on the topic how to share this cookie among other APIs, but I was shocked to find out that this cookie actually gets shared. And I do not have any specific functionality for cookie sharing. Here are screenshots of my 2 APIs running on different ports, both having the same cookie. I even compared their value and its the same. The APIs are in the same solution.
Now, the questions are 2 – why is this cookie shared among the APIs and how can I read the information for the logged user (claims) from it?
I tried to use CookieHandler abstract class which has 3 abstract methods. But the problem was that these methods had HttpContext parameter coming from System.Web namespace, whereas the HttpContext property comes from AspNetCore.Mvc.
Any advise would be appreciated, since I have no idea how to get the Identities from the cookie. Bear in mind that only the Identity.API has SignInManager/ UserManager.
2
Answers
the cookie you assign to logged in user must have information about the user claims and the scopes that user can access.
if you are using identity server, in client configuration set
AlwaysIncludeUserClaimsInIdToken = true
and the claims for the user is accessible from profile stored in access token. i dont know if you are using identity server or not so i can not go further. if you are using only identity implementation then please take look at api security with Oauth.You can get shared cookie use CookieAuthenticationEvents.
For that, you should inheritance CookieAuthenticationEvents, and override any methods with cookie context parameter, for example SigningIn method.
Also you should add scoped derived class to IServiceCollection, and add it to CookieAuthenticationOptions EventsType