2

I'm having trouble problem with web api 2.

I'm using vs2015 and have developed my project on asp.net mvc single page template that use knockout and sammy to get/authorize identity through owin middleware.

When I request for access token via default single page app.js, that is working well but if I try to get a token via postman (grant_type=password&username=admin@mail.com&password=1234) that returns invalid_cliend error.

{
  "error": "invalid_client"
}

Provider :

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
    {
        private readonly string _publicClientId;

        public ApplicationOAuthProvider(string publicClientId)
        {
            if (publicClientId == null)
            {
                throw new ArgumentNullException("publicClientId");
            }

            _publicClientId = publicClientId;
        }

        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            if (context.ClientId == _publicClientId)
            {
                Uri expectedRootUri = new Uri(context.Request.Uri, "/");

                if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                {
                    context.Validated();
                }
                else if (context.ClientId == "web")
                {
                    var expectedUri = new Uri(context.Request.Uri, "/");
                    context.Validated(expectedUri.AbsoluteUri);
                }
            }

            return Task.FromResult<object>(null);
        }

    }

Startup.Auth :

static Startup()
        {
            PublicClientId = "web";

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                //Provider = new AuthorizationServerProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
        }

        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static string PublicClientId { get; private set; }

I need your help.

Lukas Kabrt
  • 5,441
  • 4
  • 43
  • 58
tsubasaetkisi
  • 301
  • 2
  • 10
  • Ensure you're sending `grant_type=password&username=admin@mail.com&password=1234` in request body. How do you compose your request in postman? Possibly, you can use `Fiddler` to intercept the request from your `app.js` (which you say is working fine) to see how it's being sent and then compare. – Ivan Sivak Dec 24 '15 at 14:04
  • Go "Body" tab -> check to "x-www-form-urlencoded" and passing grant_type, username and password as a key/value pair. – tsubasaetkisi Dec 24 '15 at 15:33

2 Answers2

1

I think that you must override ValidateClientAuthentication instead of ValidateClientRedirectUri when you want use a grant of type password(grant_type=password).

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    //here simply call context.Validated() or add your client id validation logic

}
omar.ballerani
  • 148
  • 1
  • 2
  • 7
0

The solution for others :

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

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    // set CORS
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

    //validate to get access_token
    if (context.UserName == "admin@mail.com" && context.Password == "1234")
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);


        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
    else
    {
        context.SetError("invalid_grant", "Invalid username or password.");
    }
}
tsubasaetkisi
  • 301
  • 2
  • 10