Sam
Sam

Reputation: 73

Web API controller and MVC controller - Authentication

I have an MVC app. It also uses services exposed by Web API controller.

Hosting environment for both MVC and Web API is IIS. In IIS authentication mode set is anonymous.

HttpModule is used to set User's identity and role to Thread and HttpContext object both.

Doing all that MVC controllers are being called properly but Web API controllers return 401 unauthorized error.

appropriate authorize attribute are used in both controllers.

Below is the code used user to set user to thread and context object.

var principal = new GenericPrincipal(new GenericIdentity(userName), roles);
                // contextBase.User = principal;
                HttpContext.Current.User = principal;
                Thread.CurrentPrincipal = principal;

Upvotes: 3

Views: 1867

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239430

Web Api is REST-based. Among other things, REST is stateless, meaning no concept of a session. Authentication in MVC is handled via sessions, so simply authenticating in MVC side of the app does nothing for the Web Api side.

Each Web Api request must have all the information necessary to fulfill that request, which includes any applicable authentication/authorization. Typically with an API, this is handled by passing an authentication token in the request headers, but there's many way you can authorize an API request. I'd recommend just searching for something like "web api authentication" and reading a bit.

Long and short is that authorizing a web api endpoint requires a different and separate process from authenticating with your MVC site.

Upvotes: 5

Related Questions