I have ASP.NET MVC4 application project. I also added WebApi to my project by creating ApiContoller
. I have Forms Authentication for MVC and Basic Authentication (Thinktecture) for Web API.
I noticed that in ApiContoller [Authorize]
is working well but [Authorize(Roles="")]
never let to invoke methods. I think the reason is that in MVC Contoller
descendants both statements User.IsInRole("");
and Roles.IsUserInRole(User.Identity.Name, "");
returns true
, but in ApiContoller
descendants first statement is always false
, when second returns true
if user has role:
bool booool1 = User.IsInRole("Radiolog");
bool booool2 = Roles.IsUserInRole(User.Identity.Name, "Radiolog");
Here is my web.config configuration:
<add key="enableSimpleMembership" value="false" />
<add key="autoFormsAuthentication" value="false" />
...
<roleManager cacheRolesInCookie="false" defaultProvider="CustomRoleProvider" enabled="true">
<providers>
<clear />
<add name="CustomRoleProvider" type="RisSystem.Services.CustomRoleProvider" />
</providers>
</roleManager>
...
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
In ApiController
methods I am authenticating with: client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(login, password);
(Thinktecture) and FormsAuthentication
in MVC Contoller
.
Authentication for WebApi is set in WebApiConfig.cs
in Register(HttpConfiguration config)
function:
var authConfig = new AuthenticationConfiguration();
authConfig.AddBasicAuthentication((userName, password) => AuthenticationService.ValidateUser(userName, password));
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
Q: How to get to work Authorize Attribute with Roles in ASP.NET Web API