【问题标题】:C# OAuth OWIN: return custom response when invalid credentials provided to Token endpoint?C# OAuth OWIN:向令牌端点提供无效凭据时返回自定义响应?
【发布时间】:2016-11-11 11:00:37
【问题描述】:

我有一个通过OAuthAuthorizationServerProvider 实现身份验证的Web API 项目。我已经对提供者进行了子类化,并根据需要实现了方法来实现我自己的身份验证系统。

我还想出了如何覆盖为未经身份验证的请求提供的返回值(您必须继承 AuthorizeAttribute 类,然后在您打算保护的端点上使用您的自定义属性而不是 Authorize)。

我还可以覆盖我的 OAuth 身份验证服务器提供程序中的 TokenResponse 方法,以更改包含令牌的响应。

现在我要做的是在用户向令牌端点提供 incorrect 凭据时覆盖令牌端点提供的响应。现在,我只是明白了:

{"error":"invalid_grant","error_description":"The user name or password is incorrect."}

我知道此文本的来源 - 在我的 GrantResourceOwnerCredentials 方法中,如果请求未通过身份验证,我会执行以下操作:

if (!isValidUser)
{         
    context.SetError("invalid_grant", "The user name or password is incorrect.");
    return;
}

不过,我希望能够完全操纵用户提供不正确凭据时返回的Response 对象。

例如,我可能希望将返回设置为如下所示:

{"error":401,"timestamp":1234567890,"message":"Those credentials are wrong. Try again."}

有没有办法覆盖服务器在失败身份验证时提供的响应?

【问题讨论】:

    标签: c# asp.net oauth owin


    【解决方案1】:

    试试下面的代码,参考here

    public class CustomAccessTokenProvider : AuthenticationTokenProvider
    {
        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            context.DeserializeTicket(context.Token);
            var expired = context.Ticket.Properties.ExpiresUtc < DateTime.UtcNow;
            if (expired)
            {
                //If current token is expired, set a custom response header
                context.Response.Headers.Add("X-AccessTokenExpired", new string[] { "1" });
            }
    
            base.Receive(context);
        }
    }
    

    设置OWIN OAuth时注册:

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
                {
                    AccessTokenProvider = new CustomAccessTokenProvider()
                });
    

    【讨论】:

      【解决方案2】:

      您无法更改此行为。您只能更改context.SetError() 方法中的字段。

      在这种情况下,响应(包括状态代码)由 SendErrorAsJsonAsync() 私有方法、OAuthAuthorizationServerHandler 内部类、Microsoft.Owin.Security.OAuth dll 组成。

      您可以修改OAuthAuthorizationServerHandler类中的代码以获取更多详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-07
        • 1970-01-01
        • 2017-10-28
        • 1970-01-01
        • 1970-01-01
        • 2014-03-08
        • 2020-10-16
        • 2021-05-26
        相关资源
        最近更新 更多