我有一个 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/