title: Asp.Net WebApi OWIN Authentication
body: <p>After following an online tutorial to use token based authentication using OWIN, I managed to get my test app authenticating against a hard coded username/password, as the demo did.</p>
  
  <p>However, now I want my model from my web application to be used.</p>
  
  <p>My authentication happens, as the demo said, in this bit of code.</p>
  
  <pre><code>namespace UI
  {
      public class AuthorisationServerProvider : OAuthAuthorizationServerProvider
      {
          public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
          {
              context.Validated(); // Means I have validated the client.
          }
  
          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
              // Here we validate the user...
              var identity = new ClaimsIdentity(context.Options.AuthenticationType);
              if (context.UserName == "user" &amp;&amp; context.Password == "password")
              {
                  identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
                  identity.AddClaim(new Claim("username", "user"));
                  identity.AddClaim(new Claim(ClaimTypes.Name, "My Full Name"));
                  context.Validated(identity);
              }
              else
              {
                  context.SetError("Invalid grant", "Username or password are incorrect");
                  return;
              }
          }
  
      }
  }
  </code></pre>
  
  <p>I have a WebAPI controller, which I receive a model from, and ... not sure how to call the above code, from my webapi controller. At the moment, the code above expects a call to myurl/token - that was defined in the startup code.</p>
  
  <pre><code> public class Startup
      {
          public void Configuration(IAppBuilder app)
          {
              // Enables cors origin requests.
              app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
  
              // Config OAuth authorisation server;
  
              var myProvider = new AuthorisationServerProvider();
              OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
              {
                  AllowInsecureHttp = true, // Live version should use HTTPS...
                  TokenEndpointPath = new PathString("/token"),
                  AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                  Provider = myProvider
              };
  
              app.UseOAuthAuthorizationServer(options);
              app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
  
              HttpConfiguration config = new HttpConfiguration();
              WebApiConfig.Register(config);
          }
      }
  </code></pre>
  
  <p>So, I'm guessing the url from my webapi call should be /token? So, in my (Knockout View model) code on my UI, I tried this:</p>
  
  <pre><code> Login()
      {
          var data = {
              username : this.login.emailAddress(),
              password : this.login.password(),
              RememberMe: this.login.rememberMe(),
              grant_type: "password"
          }
  
          return $.ajax({
              type: "POST",
              data: data ? JSON.stringify(data) : null,
              dataType: "json",
              url: "/token",
              contentType: "application/json"
          }).done((reply) =&gt; {
              alert("Done!");
          });
  
      }
  </code></pre>
  
  <p>But, I get an exception:</p>
  
  <pre><code>“error”: “unsupported_grant_type”
  </code></pre>
  
  <p>In 'Postman', I am able to authenticate the hard coded username/password.</p>
  
  <p><a href="https://i.stack.imgur.com/xpCsc.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/xpCsc.jpg" alt="enter image description here"></a></p>
  
  <p>But I am not sure how to wire up my api call from my UI, to authenticate.</p>
  
  <p>I was hoping to create a 'Login' method on my api controller (ASP.Net WebAPI), like this:</p>
  
  <pre><code>[Route("login"), HttpPost, AllowAnonymous]
  public ReplyDto Login(LoginRequest login)
  {
      ReplyDto reply = _userService.Login(login.Email, login.Password);
      return reply;
  }
  </code></pre>
  
  <p>So, my _userService checks if the user is in the database... if so, call my OAuth authentication here passing a few parameters. But not sure that's possible. Can I call my authentication from this api method? I'd need to remove the /token bit though. </p>