我有一个服务,其中一些方法有PrincipalPermissionAttribute。如果主体检查失败,我希望请求身份验证。例如:
[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public string GetData()如果调用用户是管理员,服务应该返回数据。如果调用的用户不是管理员,服务应该请求身份验证,如果失败,服务应该返回401响应。我该怎么做?
发布于 2016-04-07 00:32:56
好的,我已经成功地用一个助手类完成了这个任务:
internal static class UserPermissions
{
public static bool CheckRole(Role role)
{
try {
var p = new PrincipalPermission(null, role.ToString());
p.Demand();
}
catch (SecurityException) {
return false;
}
return true;
}
public static void AssertRole(Role role)
{
if (!CheckRole(role)) {
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
}
public enum Role
{
Administrator,
Customer
}有了这样的用法:
public class CustomerService : ICustomerService
{
public List<Order> GetOrders()
{
UserPermissions.AssertRole(Role.Customer);
// Code to get orders.
}
}因此,我放弃了ping-ponging身份验证请求的想法,只返回401错误。
https://stackoverflow.com/questions/35690549
复制相似问题