Search code examples
c#.netasp.net-mvcasp.net-web-api2asp.net-identity

Identity Shared between Applications - Identity Framework C#.NET


I have 2 applications, a MVC 5 master website (A) and a Web Api 2 slave endpoint (B) hosted on two different machines accessing 1 database.

These applications should share Authentication & Authorization based on Forms Authentication. What would be the recommended way of implementing it such that once authenticated on (A):

  • The endpoint (B) starts letting through requests on controllers decorated with [Authorize] attribute
  • Http.Context.User.Identity is not NULL on (A) and (B)

I tried using an authentication cookie like so:

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieName = "DefaultCookie",
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/auth/login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
                    validateInterval:TimeSpan.FromMinutes(20),
                    regenerateIdentity: (manager,user) => user.GenerateUserIdentityAsync(manager))
            }
        });

But I haven't been exactly successful.


Solution

  • You can roll your own, but IdentityServer4 does that sort of thing. Crudely put 1) MVC authenticates; 2) MVC get Id Token; 3) Pass request to Web API with Id Token; 4) Web API checks to see if token is valid and gets claims; 5) If user is authorized, perform action; 6) repeat 3 - 5 as long as token is valid.