我有 ASP.NET MVC4 应用程序项目。我还通过创建
ApiContoller
将 WebApi 添加到我的项目中。我有用于 MVC 的表单身份验证和用于 Web API 的基本身份验证 (Thinktecture)。
我注意到在 ApiContoller 中
[Authorize]
运行良好,但 [Authorize(Roles="")]
永远不会调用方法。我认为原因是在 MVC Contoller
后代中,User.IsInRole("");
和 Roles.IsUserInRole(User.Identity.Name, "");
都返回 true
,但是在 ApiContoller
后代中,第一个语句总是 false
,如果用户有角色,第二个返回 true
:
bool booool1 = User.IsInRole("Radiolog");
bool booool2 = Roles.IsUserInRole(User.Identity.Name, "Radiolog");
这是我的 web.config 配置:
<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>
在
ApiController
方法中,我使用以下方法进行身份验证:client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(login, password);
(Thinktecture)和 FormsAuthentication
在 MVC Contoller
.
WebApi 的身份验证在
WebApiConfig.cs
中的Register(HttpConfiguration config)
函数中设置:
var authConfig = new AuthenticationConfiguration();
authConfig.AddBasicAuthentication((userName, password) => AuthenticationService.ValidateUser(userName, password));
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
问:如何在 ASP.NET Web API 中使用角色授权属性