Salick
Salick

Reputation: 27

mvc forms authentication separated from webapi authentication

I have an existing MVC 5 project wite WebAPI2 controllers. I use Forms Authentication for my frontend and now Bearer tokens for my WebAPI.

The problem is that if I use the WebAPI authentication after logging in to the MVC Application, the webapi thinks I'm authenticated even if I don't specify a valid bearer token.

If I call

config.SuppressDefaultHostAuthentication()      

then once login through WebAPI with a bearer token and then login to the MVC app, the principal is always set to ClaimsPrinciple even though it was set to my custom prinicpal (Application_AuthenticateRequest). So when I cast the HttpContext.User to my custom Prinicpal later, it doesn't work and the MVC App thinks my user is logged out.

So, how can I separate the two authentication methods without them overriding each other?

MVC Authentication:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated)
        {
            // check if we have the user in the cache
            var userPrincipal = PrincipalManager.GetPrincipal();
            if (userPrincipal == null || !userPrincipal.Identity.IsAuthenticated)
            {                    
                userPrincipal = new GenericPrincipal(new RoomixerIdentity(), null);

                PrincipalManager.StorePrincipal(userPrincipal);                    
            }


            HttpContext.Current.User = userPrincipal;
        }            
    }

Upvotes: 2

Views: 862

Answers (1)

Taiseer Joudeh
Taiseer Joudeh

Reputation: 9043

I recommend you to check the VS 2013 Web API template (Web API and MVC core dependency) but with individual accounts checked as this image, I believe you are missing adding those both lines in class WebApiConfig.cs:

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

You need to suppress the default authentication (Forms Auth) then add the bearer authentication only for Web API.

Upvotes: 1

Related Questions