2

我尝试设置自定义错误消息以从我的 OAuthBearerAuthenticationProvider 的“ValidateIdentity”代码返回。但我得到的只是

{"message":"Authorization has been denied for this request."}

这是我的代码:

internal class CustomOAuthBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
    public override async Task ValidateIdentity(OAuthValidateIdentityContext context)
    {
        context.SetError("unauthorized_client", "more infos follow");

        return;
    }
}


...

var oauthbearer = new OAuthBearerAuthenticationOptions
{
    Provider = new CustomOAuthBearerAuthenticationProvider(),


};

appBuilder.UseOAuthBearerAuthentication(oauthbearer);

是否有可能覆盖标准错误?

4

1 回答 1

0

我查看 Microsoft.Owin.Security.Jwt 源代码,发现它无法处理 Response 。你可以这样做。

public class TokenAuthorizeAttribute: AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        base.OnAuthorization(actionContext);
    }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        //Write Your Response Body ,Now I  Throw a Custom ValidateException;
        throw new TokenValidateException();
        //base.HandleUnauthorizedRequest(actionContext);
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        return base.IsAuthorized(actionContext);
    }
}

另一种方法

1.添加扩展

public static class AppBuilderExtensions
    {
        /// <summary>
        /// Jwt Authentication Extension
        /// </summary>
        /// <param name="app"></param>
        /// <param name="options"></param>
        public static void UseJwtAuthentication(this IAppBuilder app, JwtBearerAuthenticationOptions options)
        {
            app.UseJwtBearerAuthentication(options);
            app.Use<JwtToken>();
        }
    }

2.制作中间件

    using Microsoft.Owin;
    using System.Security.Principal;
    using System.Threading;
    using AppFunc = Func<IDictionary<string, object>, Task>;
    /// <summary>
    /// 访问授权验证
    /// </summary>
    public class JwtToken
    {
        AppFunc _NextFunc;

        public JwtToken(AppFunc headerAuthentication)
        {
            _NextFunc = headerAuthentication;
        }


        public async Task Invoke(IDictionary<string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);

            if (AuthorizeCore(context))
            {
                await _NextFunc.Invoke(environment);
            }else{
                 IOwinResponse response = context.Response;
                 response.StatusCode = 401;
                 response.ContentType = "application/json; charset=utf-8";
                 response.Write(string.Format("{{\"ErrCode\": 0,\"ErrMsg\": null,\"SubErrCode\": {0},\"SubErrMsg\": \"\"}}",
                 HandlerErrorStatusCode.SystemParamsValidateException));
            }
        }

        ///Check Token IsAuthenticated
        private bool AuthorizeCore(IOwinContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            IPrincipal user = httpContext.Authentication.User;
            if (user == null || !user.Identity.IsAuthenticated)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 资源的释放
        /// </summary>
        public void Dispose() { }
    }
于 2016-06-29T09:49:18.510 回答