Search code examples
c#.net-coreidentityserver4

Identity Server 4 won't use custom Authentication Handler


I have a working AuthenticationHandler<> for MVC Core and it works beautifully. Now I want to re-use the whole thing for Identity Server 4 but the framework seems to work against me.

I have added

builder.Services.AddAuthentication().AddScheme<MyWebsiteOptions, MyWebsiteAuthenticationHandler<TIdentity, MyWebsiteUser>>(CredentialStoreConstants.SCHEMA_NAME, x => { x.ConnectionString = options.ConnectionString; });

And like I said it works 100% for the MVC Core-part. Now, I cannot access IdentityServer4 endpoints like /connect/authorize/callback with it. I have already read the Identity Server 4 documentation over and over again, but somehow I am missing some key thing here.

Does anyone has an idea? I am sure I am not the first person to run into this.


Solution

  • Answer. It was more obvious than I imagined it to be.

    For the standard .NET Core Authentication, a succesfull pass at AuthenticationHandler<> in not enough

    If you have a custom usertype and custom login flow, you also need to do something like this after you succesfully verified the credentials of said custom usertype.

    At one point, you need to retrieve the corresponding user from the database and into the rest of the MVC Core authentication flow.

    So after something like AuthenticationHandler<>().Succeeded == true you need to do this:

     var systemUser = await _userResolver.GetUserAsync(user.Email);
     await _signInManager.SignInAsync(systemUser, true);
    

    The last line is the most important as it initializes a correct MVC Core user-session