无法使用Web API OWIN JWT令牌

时间:2018-01-19 22:54:01

标签: winforms authentication asp.net-web-api jwt owin

我正在使用需要使用令牌身份验证通过WebAPI进行身份验证的Windows窗体构建桌面APP。

API被证明有效,因为移动APP正在使用它,我也可以使用POSTMAN获得结果

enter image description here 问题是当我从桌面应用程序调用身份验证方法时。

当我执行请求时,API会收到该请求,并且只会在ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)之前进行,而不会在验证过程中达到GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

这是我的CustomAuthProvider

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
            context.Validated();
            return Task.FromResult<object>(null);
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var allowedOrigin = "*";
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "El nombre de usuario o contraseña son incorrectos");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
        var ticket = new AuthenticationTicket(oAuthIdentity, null);
        context.Validated(ticket);
    }
}

这是我的启动课程

 public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);

        HttpConfiguration httpConfig = new HttpConfiguration();

        ConfigureOAuthTokenGeneration(app);
        ConfigureOAuthTokenConsumption(app);
        ConfigureWebApi(httpConfig);


    }
}

目前,我尝试了两种不同的方式来验证APP。

第一个:

public LoginResponseModel Authenticate(LoginRequestModel applicationUser)
    {
        using (var client = new WebClient())
        {
            try
            {

                client.Headers["Content-Type"] = "application/json";

                var data = applicationUser.Serialize();
                var response = client.UploadString(Context.ApiUrl + "Authenticate","POST", JsonConvert.SerializeObject(applicationUser));
                var resultJson = JsonConvert.DeserializeObject<LoginResponseModel>(response);

                return resultJson;
            }
            catch (Exception exception)
            {
            }
        }
        return null;
    }

第二个:

public async Task<ApplicationUser> Authenticate(LoginRequestModel applicationUser)
    {
        var client = new HttpClient();

            try
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
            var data = applicationUser.Serialize();
                var response = await client.PostAsJsonAsync(Context.ApiUrl + "Authenticate",data );

                // return null by default (test)
                return null;
            }
            catch (Exception exception)
            {
            }
        return null;
    }

这是我用于请求的模型

public class LoginRequestModel
{
    public string Grant_type { get; set; } = "Password";
    public string UserName { get; set; }
    public string Password { get; set; }
}

这应该是回应:

public class LoginResponseModel
{
    public string Access_token { get; set; }
    public string Token_type { get; set; }
    public string Expires_in { get; set; }
}

目前,两种调用API的方式都只能到达owin进程的初始验证(ValidateClientAuthentication)。可能发生什么?我怎么解决这个问题?我需要做什么才能使流程进入GrantResourceOwnerCredentials?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。问题是表格没有填写并正确发送。

private AuthToken GetAuthToken(LoginRequestModel applicationUser)
    {
        using (var client = new HttpClient())
        {
            var form = new Dictionary<string, string>
            {
                {"grant_type", "password"},
                {"username", applicationUser.UserName},
                {"password", applicationUser.Password},
            };
            try
            {
                var tokenResponse = client.PostAsync(Context.ApiUrl + "Authenticate", new FormUrlEncodedContent(form)).Result; 
                var token = tokenResponse.Content.ReadAsAsync<AuthToken>(new[] { new JsonMediaTypeFormatter() }).Result;
               return token;
            }
            catch (Exception e)
            {
                Log4Net.log.Error("Error Getting Auth token", e);

                return null;
            }

        }
    }