0

I'm posting user credentials from a web app to the web api which implements a provider that authenticates the user and responds with a valid token.

This is the method that posts:

    public TokenModel RequestAPIToken(string username, string password)
    {
        var postData = new Dictionary<string, string>();
        postData.Add("grant_type", "password");
        postData.Add("username ", username);
        postData.Add("password ", password);

        HttpContent content = new FormUrlEncodedContent(postData);

        _response = _client.PostAsync("token", content).Result;
        var result = _response.Content.ReadAsAsync<TokenModel>().Result;

        return result;
    }

This is taken from the web api project:

public override async Task   GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var _userServices = new UserServices();
        User user = _userServices.GetValidatedUser(context.UserName, context.Password).FirstOrDefault();

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("userId", user.UserId.ToString()));
        identity.AddClaim(new Claim("username", user.Username.ToString()));

        context.Validated(identity);
    }

The problem is that context.UserName and context.Password are always null! I have tried using key value pairs instead of a dictinary and I am using _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

Any advice please?

DeanR
  • 370
  • 2
  • 13
  • Cant quite see from your code post; but does your WebApi call need to be decorated with HttpPost (I remember it defaults to HttpGet otherwise) ? – PhillipH Mar 10 '16 at 22:40
  • I have just tried putting the tag above the method - no luck. My other two methods (Post and Get) are not decorated and they both work ok without the tags – DeanR Mar 10 '16 at 22:44

2 Answers2

2

The problem couldn't be easily demonstrated from your code as it may be the null due to another reason not shown in your code.

but i would recommend to you this topic token-based-authentication-asp-net-web-api-2-owin-asp-net-identity, its a 5 parts topic that cover how to implement token based authentication from a to z and you can compare your code with it's steps as he start from scratch.

And as you mentioned that you follow his steps, he covered in part 2 how to get the token using Angular client and also in part 1 he covered how to get it using fiddler or postman so you should be sure that your post request having the needed header and body info to generate the token.

Also try to listen to your web client request using fiddler or your browser network tools and check if it's contains the proper data.

Marzouk
  • 2,650
  • 3
  • 25
  • 56
  • Yeah this is what I based my code on.. but it doesn't cover how to call the web api from within the asp.net code – DeanR Mar 10 '16 at 22:51
  • @DeanR as you mentioned that you follow his steps, he covered in part 2 how to get the token using Angular client and also in part 1 he covered how to get it using fiddler or postman so you should be sure that your post request having the needed header and body info to generate the token. – Marzouk Mar 10 '16 at 22:57
  • I am able to generate a proper response if I mock up a post with something like 'Postman'. If I use Postman and manually enter all the info and click send - then the Username and Password values are not null - they are assigned correctly. – DeanR Mar 10 '16 at 23:00
  • 1
    @DeanR try to listen to your web client request using fiddler and check if it's contains the proper data. – Marzouk Mar 10 '16 at 23:01
  • I have based my POST method on this http://stackoverflow.com/questions/15176538/net-httpclient-how-to-post-string-value. Fiddler isn't being of any help it doesn't seem to be capturing the post data sent from the application to the web api - only the post that I make when I submit the login form – DeanR Mar 10 '16 at 23:42
0

For two days I have been tearing my hair out and trying everything under the sun to get this to work.

The problem was indeed with my POST postData.Add("username ", username); postData.Add("password ", password);

There is a space after username and a space after password. I facepalmed myself pretty hard after I noticed this.. sorry for wasting your time guys.

DeanR
  • 370
  • 2
  • 13