拒绝令牌请求时自定义

拒绝令牌请求时自定义

本文介绍了拒绝令牌请求时自定义 OWIN/OAuth HTTP 状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经推导出 OAuthAuthorizationServerProvider 以验证客户端和资源所有者.

I've derived OAuthAuthorizationServerProvider in order to validate both clients and resource owners.

当我验证资源所有者时,我发现他们的凭据无效,我调用 context.Rejected()HTTP 响应带有 HTTP/400 Bad Requestem> 状态代码,而我希望 HTTP/401 Unauthorized.

When I validate resource owners I find their credentials aren't valid, I call context.Rejected(), and HTTP response comes with HTTP/400 Bad Request status code while I would expect HTTP/401 Unauthorized.

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

How can I customize OAuthAuthorizationServerProvider's response HTTP status codes?

推荐答案

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

This is how we override the OwinMiddleware...first we created our own middleware on top of Owin...I think we had similar issue as you did.

首先需要创建一个常量:

First need to create a constant:

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

我们覆盖了 OwinMiddleware

And we override the 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 文件中,我们允许覆盖调用 Owin 命令

In the startup.Auth file, we allowed the overrid of the Invoke Owin Commands

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

    }

在 ApplicationOAuthProvider 中,我们修改了 GrantResourceOwnerCredentials.

And in the ApplicationOAuthProvider, we modified the 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;
            }
            ....

这篇关于拒绝令牌请求时自定义 OWIN/OAuth HTTP 状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 10:16