aspnet / AspNetKatana

Microsoft's OWIN implementation, the Katana project
Apache License 2.0
963 stars 332 forks source link

Use two identities in the same web application #428

Closed omarmallat closed 2 years ago

omarmallat commented 3 years ago

In my ASP.NET web application, users authenticate initially with Microsoft to use the application.

At some point, user needs to authenticate also with Google to perform few queries with Google (without overriding the Microsoft identity that will continue to be used).

I noticed that whenever I use Context.GetOwinContext().Authentication.Challenge(properties, "Google"), the authentication succeeded and I can call Google's API, but the Microsoft related claims, tokens and the whole identity are lost and replaced with the Google one, and I cannot anymore call Microsoft API unless I ask users to login again.

Tratcher commented 3 years ago

To do this you need to maintain separate cookies for each provider.

Something like:

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "External-Google",
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName = CookieAuthenticationDefaults.CookiePrefix + "External.Google",
            });

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = Environment.GetEnvironmentVariable("google:clientid"),
                ClientSecret = Environment.GetEnvironmentVariable("google:clientsecret"),
                SignInAsAuthenticationType = "External-Google",
            });

And then when you want just the google claims you say var result = await Context.GetOwinContext.Authenticaiton.AuthenticateAsync("External-Google");

omarmallat commented 2 years ago

Thank you for your response. Now, I can see both claims based on your suggestion. but still there is one identity. and actually, after signing in with the second identity, User.Identity.Name became empty.

Tratcher commented 2 years ago

The sample above sets AuthenticationMode = AuthenticationMode.Passive so that HttpContext.User is not updated, it should still reflect the original Microsoft identity if you were signed in with that, you can only observe the google claims if you directly call AuthenticateAsync. If you want to maintain multiple concurrent identities everywhere then relying on HttpContext.User becomes a problem.

ghost commented 2 years ago

This issue has been resolved and has not had any activity for 1 day. It will be closed for housekeeping purposes.

See our Issue Management Policies for more information.

ghost commented 2 years ago

This issue has been resolved and has not had any activity for 1 day. It will be closed for housekeeping purposes.

See our Issue Management Policies for more information.