簡體   English   中英

如何驗證ASPF WebAPI 2的WPF客戶端請求

[英]How to authenticate WPF Client request to ASP .NET WebAPI 2

我剛剛創建了一個ASP .NET MVC 5 Web API項目,並添加了實體框架模型和其他東西,以使其與ASP一起使用 NET身份

在此輸入圖像描述

現在,我需要從WPF客戶端應用程序創建對該API的標准方法的簡單身份驗證請求。

ASP .NET MVC 5 Web API代碼

[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController

        // GET api/Account/UserInfo
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("UserInfo")]
        public UserInfoViewModel GetUserInfo()
        {
            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            return new UserInfoViewModel
            {
                UserName = User.Identity.GetUserName(),
                HasRegistered = externalLogin == null,
                LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
            };
        }

WPF客戶端代碼

public partial class MainWindow : Window
{
    HttpClient client = new HttpClient();

    public MainWindow()
    {
        InitializeComponent();

        client.BaseAddress = new Uri("http://localhost:22678/");
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json")); // It  tells the server to send data in JSON format.
    }

    private  void Button_Click(object sender, RoutedEventArgs e)
    {
        Test();
    }

    private async void Test( )
    {
        try
        {
            var response = await client.GetAsync("api/Account/UserInfo");

            response.EnsureSuccessStatusCode(); // Throw on error code.

            var data = await response.Content.ReadAsAsync<UserInfoViewModel>();

        }
        catch (Newtonsoft.Json.JsonException jEx)
        {
            // This exception indicates a problem deserializing the request body.
            MessageBox.Show(jEx.Message);
        }
        catch (HttpRequestException ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {               
        }
    }
}

它似乎正在連接到主機,我收到了正確的錯誤。 那沒問題。

響應狀態代碼不表示成功:401(未授權)。

我不知道如何使用WPF客戶端發送用戶名和密碼的主要問題...

(伙計們,我不是在問我是否必須加密它並使用Auth Filter而不是API方法實現。我會在以后確實這樣做......)

我聽說我必須在頭請求中發送用戶名和密碼...但我不知道如何使用HttpClient client = new HttpClient();

謝謝你的任何線索!

PS我是否用WebClient替換HttpClient並使用Task無法使用HttpClient對ASP.NET Web Api服務進行身份驗證 )?

您可以像這樣發送當前登錄的用戶:

    var handler = new HttpClientHandler();
    handler.UseDefaultCredentials = true;
    _httpClient = new HttpClient(handler);

然后您可以創建自己的授權過濾器

public class MyAPIAuthorizationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        //perform check here, perhaps against AD group, or check a roles based db?
        if(success)
        {
            base.OnActionExecuting(actionContext);
        }
        else
        {
            var msg = string.Format("User {0} attempted to use {1} but is not a member of the AD group.", id, actionContext.Request.Method);
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content = new StringContent(msg),
                ReasonPhrase = msg
            });
        }
    }
}

然后在控制器中要保護的每個操作上使用[MyAPIAuthorizationFilter]。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM