简体   繁体   English

在PrincipalPermission上请求授权失败

[英]Request authorization on PrincipalPermission fail

I've got a service some methods of which have PrincipalPermissionAttribute. 我有一个服务,其中某些方法具有PrincipalPermissionAttribute。 I want to request authentication if check for principal has failed. 如果检查主体失败,我想请求身份验证。 For example: 例如:

[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public string GetData()

If calling user is Administrator, service should return data. 如果呼叫用户是管理员,则服务应返回数据。 If calling user is not Administrator, service should request authentication and if it has failed, service should return 401 response. 如果呼叫用户不是管理员,则服务应请求身份验证,如果失败,则服务应返回401响应。 How can I do this? 我怎样才能做到这一点?

Okay, I've managed to do this with a helper class: 好的,我已经通过一个辅助类来做到这一点:

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
}

With such usage: 使用这种用法:

public class CustomerService : ICustomerService
{
        public List<Order> GetOrders()
        {
            UserPermissions.AssertRole(Role.Customer);
            // Code to get orders.
        }
}

So, I gave up the idea of ping-ponging authentication requests and just return 401 error instead. 因此,我放弃了ping ping身份验证请求的想法,而只返回401错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM