【问题标题】:How to authenticate WPF Client request to ASP .NET WebAPI 2如何对 ASP .NET WebAPI 2 的 WPF 客户端请求进行身份验证
【发布时间】:2014-01-02 19:41:34
【问题描述】:

我刚刚创建了一个 ASP .NET MVC 5 Web API 项目并添加了实体框架模型和其他东西以使其与ASP. NET Identity 一起工作。

现在我需要从 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 客户端发送用户名和密码的主要问题...

(伙计们,我不是在问我是否必须对其进行加密并在 API 方法实现上使用 Auth Filter。我稍后会这样做...)

听说要在请求头中发送用户名和密码……但不知道怎么用HttpClient client = new HttpClient();实现

感谢您提供任何线索!

附:我是否将HttpClient 替换为WebClient 并使用Task (Unable to authenticate to ASP.NET Web Api service with HttpClient)?

【问题讨论】:

    标签: c# wpf asp.net-web-api asp.net-mvc-5 dotnet-httpclient


    【解决方案1】:

    您可以像这样发送当前登录的用户:

        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]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 2011-10-18
      • 2011-04-13
      • 2021-11-28
      • 2015-02-26
      • 2017-12-27
      • 2011-05-20
      相关资源
      最近更新 更多