【问题标题】:Can't Authenticate desktop APP using Web API OWIN JWT Token无法使用 Web API OWIN JWT 令牌验证桌面应用程序
【发布时间】:2018-06-29 06:16:33
【问题描述】:

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

证明这个 API 是有效的,因为一个移动 APP 正在使用它,而且我可以使用 POSTMAN 获得结果

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

当我发出请求时,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);
    }
}

这是我的 Startup 课程

 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?

感谢您的帮助

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 2015-06-04
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 2021-12-09
      • 2017-08-25
      相关资源
      最近更新 更多