c# - Owin OAuth 上下文 : Frontend login sending Json

标签 c# json asp.net-web-api oauth owin

我有一个 Web API 项目使用 OAuth/Owin 来处理身份验证。

当我通过 form-urlencoded 发帖时一切正常。但是前端团队将发布 application/json,我无法更改接收此 Json 的方法。

当我想接收一个 Json 时,我通常使用 [FromBody],但这次没有用。

我的代码:

    public override async Task ValidateClientAuthentication([FromBody]OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials([FromBody]OAuthGrantResourceOwnerCredentialsContext context)
    {
        try
        {
            ....
        }
        catch (Exception e)
        {
            context.SetError("invalid_grant", "User not found");
        }
    }
}

我的 OAuth 配置:

        public static void ConfigureOAuth(IAppBuilder app, IContainer container)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true, // HTTPS == false
            TokenEndpointPath = new PathString("/security/login"),
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(2),
            Provider = container.Resolve<IOAuthAuthorizationServerProvider>()                
        };

        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }

Json 示例:

{grant_type: "password", username : "myuser", password: "mypass"}

最佳答案

读入请求体

context.Request.Body.Position = 0; // this resets the read position to 0
var payload = await new StreamReader(context.Request.Body).ReadToEndAsync();

从这里您可以获得 JSON 对象的字符串。您可以使用反序列化器将其转换为 CLR 类型。

关于c# - Owin OAuth 上下文 : Frontend login sending Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186226/

相关文章:

c# - 将 C# 控制台应用扩展为 WPF 应用

c# - 如何在c#中将xml数据转换为json

java - 在Android中解析JSON数据

c# - 将异步等待集成到同步方法中

c# - WebApi PushStreamContent 错误处理

c# - 仅在 MSCHART 折线图的数据点上显示工具提示

c# - 单元测试错误 : This function can only be invoked from LINQ to Entities

java - 使用 Jackson 处理自定义 json 中的 "Unrecognized token"异常

java - 你好,我需要帮助解析 Java 中的 JSON 文件

javascript - 如何使用Dot net core WEB API实现文件上传?