How do I ignore the Identity Framework magic and just use the OWIN auth middleware to get the claims I seek? How do I ignore the Identity Framework magic and just use the OWIN auth middleware to get the claims I seek? asp.net asp.net

How do I ignore the Identity Framework magic and just use the OWIN auth middleware to get the claims I seek?


Use the following code to setup OWIN security middlewares:

app.UseCookieAuthentication(new CookieAuthenticationOptions{    AuthenticationType = "Application",    AuthenticationMode = AuthenticationMode.Passive,    LoginPath = new PathString("/Login"),    LogoutPath = new PathString("/Logout"),});app.SetDefaultSignInAsAuthenticationType("External");app.UseCookieAuthentication(new CookieAuthenticationOptions{    AuthenticationType = "External",    AuthenticationMode = AuthenticationMode.Passive,    CookieName = CookieAuthenticationDefaults.CookiePrefix + "External",    ExpireTimeSpan = TimeSpan.FromMinutes(5),});app.UseGoogleAuthentication();

The code above sets up application cookie, external cookie and Google external login middlewares. External login middleware will convert external user login data as identity and set it to external cookie middleware. In your app, you need to get external cookie identity and convert it to external login data, then you can check it with your db user.

Here are some sample code.

Sign in with application cookie:

var authentication = System.Web.HttpContext.Current.GetOwinContext().Authentication;var identity = new ClaimsIdentity("Application");identity.AddClaim(new Claim(ClaimTypes.Name, "<user name>"));authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(identity, new AuthenticationProperties() {     IsPersistent = false});

Get application cookie identity:

var identity = System.Web.HttpContext.Current.User.Identity as ClaimsIdentity;

Get external cookie identity (Google):

var authentication = System.Web.HttpContext.Current.GetOwinContext().Authentication;var result = await authentication.AuthenticateAsync("External");var externalIdentity = result.Identity;

Extract external login data from identity:

public static ExternalLoginData FromIdentity(ClaimsIdentity identity){    if (identity == null)    {        return null;    }    Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);    if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)        || String.IsNullOrEmpty(providerKeyClaim.Value))    {        return null;    }    if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)    {        return null;    }    return new ExternalLoginData    {        LoginProvider = providerKeyClaim.Issuer,        ProviderKey = providerKeyClaim.Value,        UserName = identity.FindFirstValue(ClaimTypes.Name)    };}