0

我有一个装饰有 PrincipalPermission 要求的 RESTful (WCF) 服务。403 FORBIDDEN如果用户不担任该角色,我希望得到响应,而是得到一个400 BAD REQUEST,而不是。仔细想想,这是有道理的——SecurityException当委托人不担任该角色时,需求会触发;<authorization>它与通过web.config 中的标记授予访问权限不同。

但是,a400 BAD REQUEST没有意义......请求没有格式错误,我只是没有权限拨打电话。响应意味着我可以400修复请求并重试,但这永远不会成功。

我如何拦截或将 a 映射SecurityException到更合适的响应(最好403 FORBIDDEN)?


装饰方法:

[PrincipalPermission(SecurityAction.Demand, Role = "FST")]
public string TestNoPermissions(string NetworkId) {
    return "Call succeeded";
}

回复:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Request Error</title>
    <style>BODY { color: #000000; ...;}</style>
  </head>
  <body>
    <div id="content">
      <p class="heading1">Request Error</p>
      <p>The server encountered an error processing the request. The exception message is 'Access is denied.'. See server logs for more details. The exception stack trace is: </p>
      <p>   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)
            at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
            at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
            at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)
            at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</p>
    </div>
  </body>
</html>
4

1 回答 1

1

您可以实现一个IErrorHandler来拦截SecurityException. 然后提供一个WebFaultException状态码。

public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
    if (error is SecurityException)
    {
        var faultEx = new WebFaultException<string>("Forbidden", HttpStatusCode.Forbidden)

        fault = Message.CreateMessage(version, faultEx.CreateMessageFault(), null);
    }
}

请注意,这是未经测试的 - 安全异常有一个令人讨厌的习惯,即在框架/管道中迷路,但这个想法有点长,需要评论。

通常你会在你的自定义 IErrorHandler 中添加一个行为,它可以在你的 DI 代码或配置中进行配置。

public class ErrorHandlerBehavior : IServiceBehavior
{
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
        // not implemented
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (var dispatcherBase in serviceHostBase.ChannelDispatchers)
        {
            var dispatcher = dispatcherBase as ChannelDispatcher;

            if (dispatcher != null)
                dispatcher.ErrorHandlers.Add(new MyCustomErrorHandler());
        }
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        // not implemented
    }
}
于 2018-06-29T11:07:52.700 回答