更新时间:2022-12-11 20:53:38
标准的消息你看,这是授权已被拒绝了这一请求。由授权
过滤器创建的。在 HandleUnauthorizedRequest
方法在响应设置此消息。
The standard message you see, which is "Authorization has been denied for this request." is created by the Authorize
filter. The HandleUnauthorizedRequest
method sets this message in the response.
protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw Error.ArgumentNull("actionContext");
}
actionContext.Response = actionContext.ControllerContext.Request
.CreateErrorResponse(
HttpStatusCode.Unauthorized,
SRResources.RequestNotAuthorized);
}
SRResources.RequestNotAuthorized
是你所看到的是标准的消息。
SRResources.RequestNotAuthorized
is what you see as the standard message.
现在, ApplyChallengeResponseAsync
从卡塔纳autentication微架构的 OnSendingHeaders
回调调用。当组件写入响应流回调被调用。在我们的例子中,当过滤器(你看到的上面)创建的响应消息被序列化,即当调用回调函数和 ApplyChallengeResponseAsync
运行。到那个时候,已经是为时已晚,你改变的响应。***的办法将是覆盖授权
过滤器的虚方法上面这个样子。
Now, ApplyChallengeResponseAsync
is called from the OnSendingHeaders
callback in Katana autentication micro framework. This callback is invoked when a component writes into the response stream. In our case, when the response message created by the filter (what you see above) gets serialized, that is when the callback is invoked and ApplyChallengeResponseAsync
runs. By that time, it is already too late for you to change the response. The best bet will be to override the virtual method of the Authorize
filter above like this.
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var response = actionContext.Request.CreateResponse<MyError>
(new MyError() { Description = "My failing reason" });
response.StatusCode = HttpStatusCode.Unauthorized;
actionContext.Response = response;
}
}
public class MyError
{
public string Description { get; set; }
}
而不是使用 [授权]
的控制器或操作方法,使用 [MyAuthorize]
。
Instead of using [Authorize]
on the controller or action method, use [MyAuthorize]
.