I'm still learning the Identity Framework and am pretty lost in trying to setup authentication in my .Net Core 2 MVC application. Any suggestions are appreciated since I'm not even sure what I'm doing is correct.
I have a requirement to integrate an OpenID Connect identity provider for authentication and use a secondary data source for authorization. Inconveniently I cannot use any claim from the OIDC IdP except for the name claim. The rest of the user claims must come from the secondary data source (which is connected to the Identity Framework through a custom UserStore
and User
entity).
I am using the OpenId Connect provider to handle the authentication. This is working fine and gives me the first Identity (which I can only use one Claim from). My confusion starts when I need to fetch the second Identity of the user, add it to the principal, and set it as the default Identity
. This second Identity
provides all of the user claims, including role.
My understanding of identity framework is that I should have a single ClaimsPrincipal
with two identities so that I can plug into the rest of Identity Framework. However with two identities the default ClaimsPrincipal
will automatically select the first Identity (which is the one I can't use), therefor it seems I should create a custom ClaimsPrincipal
and set the PrimaryIdentitySelector
so that my second Identity is the primary.
public class MyClaimsPrincipal : ClaimsPrincipal
{
private static readonly Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> IdentitySelector = SelectPrimaryIdentity;
/// <summary>
/// This method iterates through the collection of ClaimsIdentities and chooses an identity as the primary.
/// </summary>
private static ClaimsIdentity SelectPrimaryIdentity(IEnumerable<ClaimsIdentity> identities)
{
// Find and return the second identity
}
}
Once I get the validated token from the OIDC IdP, I fetch the second identity, create a new MyClaimsPrincipal, add the two Identities to the new principal. After that I'm not sure what to do with this new principal.
I've tried to sign the user in via the SignInManager
, setting the User on the HTTP context explicitly, and using middleware to convert ClaimsPrincipals
to MyClaimsPrincipals
but all of these seem to do nothing. I think I am missing the point.
Some specific questions:
- Is this the best way to do this? Being generally confused about all of this makes it hard to tell if I'm even on the right track.
- Once I've created a custom principal, how to I "set" it into the HTTP context so that it's persistent?
- How does Cookie authentication work with OpenId Connect authentication? It seems OIDC somehow passes the user into Cookie authentication, and that adding cookie authentication is required for OIDC authentication to work.