Search code examples
c#asp.netasp.net-coreasp.net-identity

Using SignInManager without calling app.UseIdentity()


I need to use basic SignIn mechanism to log in user to my website:

var result = await _signInManager.PasswordSignInAsync(username, password, false, lockoutOnFailure: false);

Unfortunately it throws an error:

No authentication handler is configured to handle the scheme: Identity.Application

The reason probably is: I'm not calling app.UseIdentity(); in Startup.cs.

I'm not calling it, because I want to configure cookies on my own. So instead of UseIdentity I use this:

        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = false,
            TokenValidationParameters = tokenValidationParameters
        });

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = false,
            AuthenticationScheme = "Cookie",
            CookieName = "access_token",
            TicketDataFormat = new CustomJwtDataFormat(
                SecurityAlgorithms.HmacSha256,
                tokenValidationParameters)
        });

If I call app.UseIdentity();, PasswordSignInAsync works correctly, but CookieAuthentication behaves like it is configured in UseIdentity (it redirects to /Account/Login, this behaviour is disabled in my configuration).

As I see in source code, UseIdentity doesn't do more than I do (it simply use UseCookieAuthentication, so similarly as I do). Why then, my soultion causes problems?

What should I do to make PasswordSignInAsync work witout using app.UseIdentity()?


Solution

  • It does do some things different, it uses IdentityOptions to set the cookie middleware and those same identityoptions are used elsewhere within signInManager when authenticating a user.

    Specifically it uses "Identity.Application" as the name of the auth scheme for the application cookie, since it uses that also when it tries to authenticate the user it throws an error because there is no cookie middleware matching the authscheme since you are naming yours differently.

    If you name your AuthenticationScheme and CookieName "Identity.Application" then it should get past that error.

    Or you can configure the IdentityOptions to match the authenticationscheme and cookiename of your choice, so that matching values are passed in from signinManager when it tries to authenticate the user