title: Send Response using OWIN Middleware Web API
body: <p><br>
  I am trying to customize access token json object in my Web APi 2 project.
  Which I have done successfully. But I am unable to figure out the case of failed request.</p>
  
  <p>Here is my custom response:-<br>
      <code>{ data: {}, success: 0, message: "failed" }</code>
  <br></p>
  
  <p>And following is a <code>GrantResourceOwnerCredentials</code> methon in <code>ApplicationOAuthProvider</code> which inherits <code>OAuthAuthorizationServerProvider</code></p>
  
  <pre><code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
      {
      ApplicationUserManager userManager = context.OwinContext.GetUserManager&lt;ApplicationUserManager&gt;();
      ApplicationUser user = userManager.Find(context.UserName, context.Password);
      bool reqFailed = false;
      string reqFailedMsg = "";
  
      if (user == null)
      {
          reqFailed = true;
          reqFailedMsg = "The user name or password is incorrect.";
      }
  
      if (!reqFailed &amp;&amp; !user.EmailConfirmed)
      {
          reqFailed = true;
          reqFailedMsg = "The user email is not confirmed.";
          //context.SetError("invalid_grant", "The user email is not confirmed.");
          //return;
      }
  
      if (!reqFailed &amp;&amp; !user.IsActive)
      {
          reqFailed = true;
          reqFailedMsg = "The user is disabled.";
          //context.SetError("invalid_grant", "The user is disabled.");
          //return;
      }
  
      if (reqFailed)
      {
          try
          {
              context.Response.Headers.Add(LMS.Utilities.Constants.MyMiddlewareHeader, new[] { (400).ToString() });
              context.Response.Headers.Add(LMS.Utilities.Constants.MyMiddlewareHeaderMsg, new[] { reqFailedMsg });
          }
          catch (Exception ex)
          {
          } 
          return;
      }
  
      var form = await context.Request.ReadFormAsync();
  
      if (form["deviceType"] != null &amp;&amp; form["deviceToken"] != null)
      {
          user.DeviceToken = form["deviceToken"];
          user.DeviceType = form["deviceType"];
  
          userManager.Update(user);
      }
  
      ClaimsIdentity oAuthIdentity = userManager.GenerateUserIdentity(userManager, user,
          OAuthDefaults.AuthenticationType);
      ClaimsIdentity cookiesIdentity = userManager.GenerateUserIdentity(userManager, user,
          CookieAuthenticationDefaults.AuthenticationType);
  
      AuthenticationProperties properties = CreateProperties(user.UserName);
      AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
      context.Validated(ticket);
      //context.Request.Context.Authentication.SignIn(cookiesIdentity);
      context.Request.Context.Authentication.SignIn(properties, cookiesIdentity);
      //return Task.FromResult&lt;object&gt;(null);
      }
  </code></pre>
  
  <p><br></p>
  
  <p>And middleware class:-<br></p>
  
  <pre><code>public class AuthenticationMiddleware : OwinMiddleware
  {
      public AuthenticationMiddleware(OwinMiddleware next) : base(next) { 
  
      }
  
      public override async Task Invoke(IOwinContext context)
      {
          await Next.Invoke(context);
          if (context.Response.Headers.ContainsKey(Constants.MyMiddlewareHeader))
          {
              using (var reader = new StreamReader(context.Request.Body))
              {
                  var headerValues = context.Response.Headers.GetValues(Constants.MyMiddlewareHeader);
                  context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
                  context.Response.Headers.Remove(Constants.MyMiddlewareHeader);
  
                  var headerValuesMessage = context.Response.Headers.GetValues(Constants.MyMiddlewareHeaderMsg);
                  string msg = headerValuesMessage.FirstOrDefault().ToString();
                  context.Response.Headers.Remove(Constants.MyMiddlewareHeaderMsg);
  
                  string resp = Newtonsoft.Json.JsonConvert.SerializeObject(new ResponseViewModel&lt;object&gt;(new { }, (int)ResponseStatus.Fail, msg));
  
                  var response = context.Response;
                  var body = await reader.ReadToEndAsync();
                  var bytes = Encoding.UTF8.GetBytes(resp);
  
                  response.ContentLength = bytes.Length;
                  await response.WriteAsync(bytes);
  
                  return;
              }
          }
      }
  }
  </code></pre>
  
  <p>What I am getting in respose is:-<br></p>
  
  <pre><code>{"error":"invalid_grant"}{"Data":{},"Status":0,"Message":"The user name or
  </code></pre>
  
  <p>Which is invalid json as you can see.</p>
  
  <p>Any help would be appreciated.
  Thanks!</p>