What is CookieAuthenticationOptions.AuthenticationType used for?

12,004

Solution 1

This is a string and can be anything. But this is an identifier for authentication type. And you can have multiple authentication types: your DB with users, Google, Facebook, etc. As far as I remember this is added as a claim to the generated cookie on sign-in.

You need to know the authentication provider when you sign user out. If your authentication middleware is defined like this:

    app.UseCookieAuthentication(new CookieAuthenticationOptions {
        LoginPath = new PathString("/Login/"),
        AuthenticationType = "My-Magical-Authentication",
        // etc...
        },
    });

then to sign user out you need the same magic string: AuthenticationManager.SignOut("My-Magical-Authentication")

Also this string is passed into ClaimsIdentity when principal is created. And without AuthenticationType principal can't be authenticated because:

/// <summary>
/// Gets a value that indicates whether the identity has been authenticated.
/// </summary>
/// 
/// <returns>
/// true if the identity has been authenticated; otherwise, false.
/// </returns>
public virtual bool IsAuthenticated
{
  get
  {
    return !string.IsNullOrEmpty(this.m_authenticationType);
  }
}

This method IsAuthenticated is used through entire MVC code-base, with all authentication mechanisms relying on this.

Also theoretically you can sign in through multiple providers and sign out only a single one of them at a time, leaving the rest of providers still authenticated. Though I have never tried this.

Another use I just found - if you don't provide CookieName in your middleware configuration, then Options.CookieName = CookieAuthenticationDefaults.CookiePrefix + Options.AuthenticationType; (see second if statement in constructor).

I'm sure there are more places where it is used. But the most important is to provide it and be consistent with the name or you'll get subtle bugs in authentication system.

Solution 2

I don't know the whole answer, but I have an example on what it would be useful for.

I have a multi-tenant website: the website runs as a single instance multiple domains are linked to it. Each domain is a separate tenant (with a separate set of users). To implement a Facebook login per tenant, I needed a Facebook app per tenant. To configure this, I had to set a unique CallbackPath and a unique AuthenticationType per tenant:

var facebookOptions = new FacebookAuthenticationOptions
{
    AuthenticationType = "Facebook-{tenantID}", 
    CallbackPath = new PathString($"/signin-facebook-{tenantID}")
}

I thought it was also used as a cookie name, but that's not the case for an external login like FacebookAuthentication. What I did notice is that this value of AuthenticationType popped up when requesting:

  1. the IdentityUserLogin.LoginProvider via authenticationManager.GetExternalLoginInfoAsync()
  2. the AuthenticationDescription.AuthenticationType via authenticationManager.GetExternalAuthenticationTypes() (seems logical ;-))
  3. The IdentityUserLogin.LoginProvider for each user.Logins (similar to 1)

And last but not least: the value of AuthenticationType is stored in the database column AspNetUserLogins.LoginProvider.

Solution 3

If you set up a fresh asp.net solution, the standard set-up code (as opposed to the code you copied from another app) in Startup.Auth includes the line AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

This creates a cookie (with a default name of .AspNet.ApplicationCookie), which you can see if you look in your browser's active cookie list, that is used (amongst other things) to check whether or not the User is Authenticated for every request. If the cookie is not there (or the User is in some way not Authenticated), the middleware redirects to the route specified in your line LoginPath = new PathString("/Login/"),

The fact that this line is commented out in your code and your app works suggests that there is some other non-standard configuration in place in your code to authenticate the User. If you uncomment this line and login succeeds but redirects back to login, this suggests that there is some conflict between the non-standard code and the middleware that results in the middleware determining that the User is not Authenticated, and gets redirected back to the LoginPath.

I would seek out whether there is non-standard authentication code in your app and determine what that specifically does, and the answer for the conflict should present itself. General advice is not to change the standard Authentication code unless you know exactly what the implications of doing this are (and it can get complicated, with plenty of traps for the unwary).

Specifically to your question, this option is not just useful, it is fundamental to standard operation of the Identity middleware. You appear to have non-standard code in your app. If so, you should fully determine what it does (and it's implications) with regards to login security, or revert back to standard Identity code if you can.

Share:
12,004
Abhishek
Author by

Abhishek

I have been a senior developer with a focus on architecture, simplicity, and building effective teams for over ten years. As a director at Surge consulting I was involved in many operational duties and decisions and - in addition to software development duties - designed and implemented an interview processes and was involved in community building that saw it grow from 20 to about 350 developers and through an acquisition. I was then CTO setting up a dev shop at working closely with graduates of a coding bootcamp on both project work and helping them establish careers in the industry. Currently a Director of Engineering at findhelp.org your search engine for finding social services. I speak at conferences, have mentored dozens of software devs, have written popular articles, and been interviewed for a variety of podcasts and publications. I suppose that makes me an industry leader. I'm particularly interesting in companies that allow remote work and can check one or more of the following boxes: Product companies that help people in a non-trite manner (eg I'm not super interested in the next greatest way to get food delivered) Product companies that make developer or productivity tooling Funded startups that need a technical co-founder Functional programming (especially Clojure or Elixir) Companies trying to do something interesting with WebAssembly

Updated on June 12, 2022

Comments

  • Abhishek
    Abhishek almost 2 years

    In my application's Asp.Net Identity Auth middleware setup I have

    app.UseCookieAuthentication(new CookieAuthenticationOptions {
        LoginPath = new PathString("/Login/"),
        //AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        Provider = new CookieAuthenticationProvider {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MyUserManager, MyUser>(
                            TimeSpan.FromMinutes(30),
                            (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)
                        ),
        },
    });
    

    I had copied this from another app and I just noticed that if I uncomment the AuthenticationType line, login succeeds (I get a success message in my logger written from my controller) but always redirects back to the login screen.

    In the documentation for CookieAuthenticationOptions it says

    The AuthenticationType in the options corresponds to the IIdentity AuthenticationType property. A different value may be assigned in order to use the same authentication middleware type more than once in a pipeline.(Inherited from AuthenticationOptions.)

    I don't really understand what this means, why this would cause my login request to be redirected (after a successful login no less), nor what this option would be useful for.