Web API token authentication

2019-06-09 02:55发布

问题:

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?

回答1:

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.



回答2:

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.