You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改OAuth授权错误响应的JSON返回字段格式

自定义OAuth密码模式错误响应格式实现方法

核心逻辑是拦截OAuth中间件默认的错误序列化流程,替换为目标字段结构,有两种实现方式可按需选择。


方式1:仅修改密码模式校验失败的响应

直接调整GrantResourceOwnerCredentials方法内的校验失败分支,手动写入自定义格式响应,屏蔽默认输出:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);

    using (UserAuthentication objUser = new UserAuthentication())
    {
        var user = objUser.ValidateUser(context.UserName, context.Password);
        if (user == "false")
        {
            // 清空默认错误配置,阻止中间件生成默认格式响应
            context.SetError(string.Empty);
            
            // 构造自定义响应结构
            var customError = new
            {
                Message = "invalid_grant",
                Message_Description = "Username or password is incorrect"
            };

            // 写入响应
            context.Response.StatusCode = 200;
            context.Response.ContentType = "application/json;charset=utf-8";
            await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(customError));
            return;
        }
        else
        {                   
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            await Task.Run(() => context.Validated(identity));
        }
    }
}

方式2:全局统一所有OAuth相关错误的响应格式

如果需要把所有OAuth流程的错误(比如无效客户端、token过期、权限不足等)都统一为Message/Message_Description的结构,可以在OAuth服务初始化配置时,拦截Challenge响应统一处理:

var oAuthOptions = new OAuthAuthorizationServerOptions
{
    // 保留原有配置:TokenEndpointPath、AccessTokenExpireTimeSpan、AllowInsecureHttp等
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    AllowInsecureHttp = true,
    
    // 替换为自定义授权提供器,增加全局错误拦截
    Provider = new YourCustomOAuthProvider() // 即你重写了GrantResourceOwnerCredentials的类
    {
        OnApplyChallengeResponse = context =>
        {
            // 取出中间件生成的默认错误信息
            var errorCode = context.Error;
            var errorMsg = context.ErrorDescription;
            
            // 清空默认响应内容
            context.Response.Clear();
            context.Response.StatusCode = 200;
            context.Response.ContentType = "application/json;charset=utf-8";
            
            // 写入自定义格式
            var customError = new
            {
                Message = errorCode,
                Message_Description = errorMsg
            };
            context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(customError)).Wait();
            
            return Task.CompletedTask;
        }
    }
};

使用全局拦截方式后,GrantResourceOwnerCredentials里的校验失败逻辑不需要手动写响应,保持原有context.SetError("invalid_grant", "Username or password is incorrect")写法即可,中间件会自动转换为目标响应结构。


内容的提问来源于stack exchange,提问作者Rajesh Sawant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 05:33:22