c# - 拒绝 token 请求时自定义 OWIN/OAuth HTTP 状态代码

标签 c# .net http oauth owin

我导出了 OAuthAuthorizationServerProvider为了验证客户端和资源所有者。

当我验证资源所有者时,我发现他们的凭据无效,我调用 context.Rejected()HTTP 响应随附 HTTP/400 错误请求 状态代码,而我期望 HTTP/401 Unauthorized

如何自定义 OAuthAuthorizationServerProvider 的响应 HTTP 状态代码?

最佳答案

这就是我们覆盖 OwinMiddleware 的方式...首先我们在 Owin 之上创建了我们自己的中间件...我认为我们遇到了与您类似的问题。

首先需要创建一个常量:

public class Constants
{
    public const string OwinChallengeFlag = "X-Challenge";
}

然后我们覆盖 OwinMiddleware

public class AuthenticationMiddleware : OwinMiddleware
{
    public AuthenticationMiddleware(OwinMiddleware next) : base(next) { }

    public override async Task Invoke(IOwinContext context)
    {
        await Next.Invoke(context);

        if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey(Constants.OwinChallengeFlag))
        {
            var headerValues = context.Response.Headers.GetValues(Constants.OwinChallengeFlag);
            context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
            context.Response.Headers.Remove(Constants.OwinChallengeFlag);
        }

    }
}

在 startup.Auth 文件中,我们允许覆盖 Invoke Owin 命令

public void ConfigureAuth(IAppBuilder app)
    ....
        app.Use<AuthenticationMiddleware>(); //Allows override of Invoke OWIN commands
    ....

    }

并且在 ApplicationOAuthProvider 中,我们修改了 GrantResourceOwnerCredentials。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (UserManager<IdentityUser> userManager = _userManagerFactory())
        {
            IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                context.Response.Headers.Add(Constants.OwinChallengeFlag, new[] { ((int)HttpStatusCode.Unauthorized).ToString() }); //Little trick to get this to throw 401, refer to AuthenticationMiddleware for more
                //return;
            }
            ....

关于c# - 拒绝 token 请求时自定义 OWIN/OAuth HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30222952/

相关文章:

c# - 使用 WMI 识别哪个设备导致了 Win32_DeviceChangeEvent

c# - 定义具有 1 个以上原型(prototype)的函数

c# 字符串性能 - 比较字符串文本或字符串长度哪个更快

c# - 如何自动刷新excel公式?

.net - Azure Cmdlet : String was not recognized as a valid Boolean

c - 通过 HTTP 向网站发送数据

c# - 组合框仅在本地正确显示

.net - 限制数字字符数的正则表达式是什么?

node.js 是什么导致错误 400 错误请求

c - SOAP 请求和响应使用 libcurl - C 读取文件或写入文件