How to get error message returned by DotNetOpenAuth.OAuth2 on client side?

后端 未结 3 1466
Happy的楠姐
Happy的楠姐 2020-12-13 07:07

I\'m using ExchangeUserCredentialForToken function to get the token from the Authorization server. It\'s working fine when my user exists in my databas, but whe

3条回答
  •  囚心锁ツ
    2020-12-13 07:37

    After hours of searching the web and reading blobs, and the owin documentation, I have found a way to return a 401 for a failed login attempt.

    I realize adding the header below is a bit of a hack, but I could not find any way to read the IOwinContext.Response.Body stream to look for the error message.

    First of all, In the OAuthAuthorizationServerProvider.GrantResourceOwnerCredentials I used SetError() and added a Headers to the response

    context.SetError("Autorization Error", "The username or password is incorrect!");
    context.Response.Headers.Add("AuthorizationResponse", new[] { "Failed" });
    

    Now, you have a way to differentiate between a 400 error for a failed athentication request, and a 400 error caused by something else.

    The next step is to create a class that inherits OwinMiddleware. This class checks the outgoing response and if the StatusCode == 400 and the Header above is present, it changes the StatucCode to 401.

    public class InvalidAuthenticationMiddleware : OwinMiddleware
    {
        public InvalidAuthenticationMiddleware(OwinMiddleware next) 
            : base(next)
        {
        }
    
        public override async Task Invoke(IOwinContext context)
        {
            await Next.Invoke(context);
    
            if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey("AuthorizationResponse"))
            {
                context.Response.Headers.Remove("AuthorizationResponse");
                context.Response.StatusCode = 401;
            }
        }
    }
    

    The last thing to do is in your Startup.Configuration method, register the class you just created. I registered it before I did anything else in the method.

    app.Use();
    

提交回复
热议问题