+-
从WPF客户端访问安全的Web API
我有一个针对API进行配置的Web API项目,并在其中一个APIController上实现了[Authorize].删除[Authorize]时,可以从 WPF客户端访问API,但是当安装到位时,调用似乎丢失了.这就是我设置的请求令牌的步骤.

在WPF代码后面

    internal void RefreshRecentFilesList()
    {
        //Get the token
        var token = GetAPIToken(email, password, "http://localhost:50006").Result;
        MessageBox.Show(token);
    }

    private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
    {
        using (var client = new HttpClient())
        {
            //setup client
            client.BaseAddress = new Uri(apiBaseUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.AccessToken);

            //setup login data
            var formContent = new FormUrlEncodedContent(new[]
             {
             new KeyValuePair<string, string>("grant_type", "password"), 
             new KeyValuePair<string, string>("username", userName), 
             new KeyValuePair<string, string>("password", password), 
             });

            //send request
            HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);

            //get access token from response body
            var responseJson = await responseMessage.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(responseJson);
            return jObject.GetValue("access_token").ToString();
        }
    }

在Web API项目中
WebAPIConfig.cs

        //Enable CORS
        var cors = new EnableCorsAttribute("*", "*", "GET");
        config.EnableCors(cors);

在API控制器中

    [HttpGet]
    //[Authorize]
    public List<FileInfo> GetFileTypes()
    {
        List<FileInfo> fileInfos = new List<FileInfo>();
        ...

在StartAuth.cs中

public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

当我运行WPF并逐步执行代码时,它到达了发送请求行,然后挂起.

谁能指出我正确的方向?

非常感谢

最佳答案
我认为您的问题的主要候选人是这一行:

var token = GetAPIToken(email, password, "http://localhost:50006").Result;

您正在调用异步方法,然后同步等待其结果:这将导致死锁.绝对不要那样做.

相反,将您的方法(以及整个调用堆栈)变为异步的.如果您在WPF中,则几乎可以肯定是从某种事件处理程序回调中调用此方法.这些回调支持异步(即使它们必须返回void).

将您的代码更改为与此类似的代码,然后重试(假设Form_Load是事件处理程序回调):

private async void Form_Load(object sender, EventArgs e)
{
    await RefreshRecentFilesList();
}

internal async Task RefreshRecentFilesList()
{
    //Get the token
    var token = await GetAPIToken(email, password, "http://localhost:50006");
    MessageBox.Show(token);
}

参考文献:
Why does this async action hang?
How to call asynchronous method from synchronous method in C#?

点击查看更多相关文章

转载注明原文:从WPF客户端访问安全的Web API - 乐贴网