Custom [Authorize] message on 401

与世无争的帅哥 提交于 2019-12-11 04:07:12

问题


I need to deliver custom "not authorized" message in different languages, instead of the default "Authorization has been denied for this request". I'm using Owin as authentication and the [Authorize] attribute for ApiControllers/methods. I know that this could be done with a custom autorization filter, but it seems an overkill situation just to change the message sent to the client.

Is there a simpler way of changing the message or should I stick to a custom authorize filter?

Thanks


回答1:


Unfortunately It is not possible.

Based on the source code, one option would be to create a new custom Authorize attribute, inheriting from AuthorizeAttribute. You then would only need to override the HandleUnauthorizedRequest method, and replace with your own. The rest of the methods would be still handled by the base AuthorizeAttribute

  public class MyCustomAuthAttribute : AuthorizeAttribute
  {
      protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw Error.ArgumentNull("actionContext");
            }

                actionContext.Response =
                actionContext.ControllerContext.Request.CreateErrorResponse(
                                      HttpStatusCode.Unauthorized, 
                                      "My Un-Authorized Message");
      }
    } 


来源:https://stackoverflow.com/questions/42378644/custom-authorize-message-on-401

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!