本文介绍了Web API令牌认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在将用户凭据从Web应用程序发布到Web api,该Web api实现了对用户进行身份验证并使用有效令牌进行响应的提供程序.

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.

这是发布方法:

    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;
    }

这取自网络api项目:

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);
    }

问题在于context.UserName和context.Password始终为null!我尝试使用键值对而不是字典,并且正在使用_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

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"));

有什么建议吗?

推荐答案

该问题无法从您的代码中轻松演示,因为由于未在代码中显示其他原因,该问题可能为null.

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.

但我会向您推荐此主题基于令牌的身份验证-asp-net-web-api-2-owin-asp-net-identity ,其5个主题,涵盖了如何实现令牌从a到z的身份验证,您可以将代码与其从头开始时的步骤进行比较.

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.

正如您提到您遵循他的步骤一样,他在第2部分中介绍了如何使用Angular客户端获取令牌,在第1部分中,他介绍了如何使用提琴手或邮递员获取令牌,因此您应确保自己的发布请求具有生成令牌所需的标题和正文信息.

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.

还尝试使用提琴手或浏览器网络工具监听您的Web客户端请求,并检查其是否包含正确的数据.

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.

这篇关于Web API令牌认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:58