请求对 PrincipalPermission 的授权失败
本文关键字:授权 失败 PrincipalPermission 请求 | 更新日期: 2023-09-27 18:36:42
我有一个服务,其中一些方法具有PrincipalPermissionAttribute。如果主体检查失败,我想请求身份验证。例如:
[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public string GetData()
如果调用用户是管理员,则服务应返回数据。如果调用用户不是管理员,则服务应请求身份验证,如果失败,服务应返回 401 响应。我该怎么做?
好的,我已经设法用一个辅助类来做到这一点:
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.
}
}
因此,我放弃了乒乓身份验证请求的想法,而只是返回401错误。