2
votes

I have a Web API project using OAuth/Owin to deal with authentication.

Everything is working fine when i post through form-urlencoded. But the frontend team will post application/json, and i was not able to change my method to receive this Json.

I usually use [FromBody] when i want to recieve a Json, but it didn't work this time.

My code:

    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");
        }
    }
}

My OAuth Config:

        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 Example:

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

1
You can read your json form request. dynamic obj = await Request.Content.ReadAsAsync<JObject>(); - Eins

1 Answers

0
votes

Read in the request body by

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

From here you have the string of your JSON object. You can use a deserializer to convert it to a CLR type.