2

I try to set a custom error message to return from "ValidateIdentity" Code from my OAuthBearerAuthenticationProvider. But All I get back is

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

This is my Code:

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);

Is there any possibility to overwrite the standard error?

rudimenter
  • 3,242
  • 4
  • 33
  • 46

1 Answers1

0

I look the Microsoft.Owin.Security.Jwt source code,find it cant't handle the Response . You can do it in this way .

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);
    }
}

the other way

1.add Extension

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.make Middleware

    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() { }
    }
Nothing
  • 1
  • 2