tsubasaetkisi
tsubasaetkisi

Reputation: 311

Get Access Token Asp.NET Web Api 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&[email protected]&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.

Upvotes: 2

Views: 1452

Answers (2)

tsubasaetkisi
tsubasaetkisi

Reputation: 311

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 == "[email protected]" && 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.");
    }
}

Upvotes: 0

omar.ballerani
omar.ballerani

Reputation: 158

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

}

Upvotes: 1

Related Questions