如何验证 WPF 客户端对 ASP .NET WebAPI 2 的请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20890539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to authenticate WPF Client request to ASP .NET WebAPI 2
提问by Developer
I just created an ASP .NET MVC 5 Web APIproject and added the Entity Framework model and other things to get it working with ASP. NET Identity.
我刚刚创建了一个ASP .NET MVC 5 Web API项目并添加了实体框架模型和其他东西以使其与ASP一起工作。NET 身份。


Now I need to create a simple authenticated request to the standard method of that API out there from the WPF Client app.
现在我需要从 WPF 客户端应用程序创建一个简单的经过身份验证的请求,该请求指向该 API 的标准方法。
ASP .NET MVC 5 Web API code
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 Client code
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
{
}
}
}
It seems like it is connecting to the host and I am getting the correct error. That is ok.
它似乎正在连接到主机,但我收到了正确的错误。那没问题。
Response status code does not indicate success: 401 (Unauthorized).
响应状态代码不表示成功:401(未授权)。
The main problem that I am not sure how to send username and password using WPF Client...
我不确定如何使用 WPF 客户端发送用户名和密码的主要问题...
(Guys, I am not asking whether I have to encrypt it and use Auth Filter over API method implementations. I will do this for sure later...)
(伙计们,我不是问我是否必须加密它并在 API 方法实现上使用身份验证过滤器。我稍后会这样做......)
I heard that I have to send username and password in the header request... but I don't know how it can be done by using HttpClient client = new HttpClient();
我听说我必须在标头请求中发送用户名和密码...但我不知道如何使用 HttpClient client = new HttpClient();
Thanks for any clue!
感谢您提供任何线索!
P.S. Have I replace HttpClientwith WebClientand use Task(Unable to authenticate to ASP.NET Web Api service with HttpClient)?
PS我已取代HttpClient用WebClient和使用Task(无法与HttpClient的认证到的ASP.NET Web API服务)?
采纳答案by Allan Elder
You can send over the current logged on user like so:
您可以像这样发送当前登录的用户:
var handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
_httpClient = new HttpClient(handler);
then you can create your own authorization filter
然后您可以创建自己的授权过滤器
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
});
}
}
}
then use [MyAPIAuthorizationFilter] on each action in your controller that you want to secure.
然后在您要保护的控制器中的每个操作上使用 [MyAPIAuthorizationFilter]。

