如何验证WPF客户端请求ASP .NET的WebAPI 2 [英] How to authenticate WPF Client request to ASP .NET WebAPI 2
问题描述
我刚刚创建一个 ASP .NET MVC的Web 5 API 项目,并增加了实体框架模型和其他的东西得到它的ASP。 NET身份。
I just created an ASP .NET MVC 5 Web API project and added the Entity Framework model and other things to get it working with ASP. NET Identity.
现在我需要创建一个简单的身份验证请求,该API从WPF客户端应用程序在那里的标准方法。
Now I need to create a simple authenticated request to the standard method of that API out there from the WPF Client app.
ASP .NET MVC的Web 5 API code
[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客户端code
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.
响应状态code并不表示成功:401
Response status code does not indicate success: 401 (Unauthorized).
这我不知道如何使用发送用户名和密码的主要问题WPF客户端...
The main problem that I am not sure how to send username and password using WPF Client...
(伙计们,我不是问我是否加密,并使用了API方法实现验证过滤器。我会做这个肯定后...)
(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...)
听说我要在头请求中发送用户名和密码...但我不知道如何可以用做 HttpClient的客户端=新的HttpClient();
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();
感谢您的任何线索!
P.S。我已经取代的HttpClient
与 Web客户端
,并使用任务
(<一个href=\"http://stackoverflow.com/questions/10308938/unable-to-authenticate-to-asp-net-web-api-service-with-httpclient\">Unable与HttpClient的来验证的ASP.NET Web API服务)?
P.S. Have I replace HttpClient
with WebClient
and use Task
(Unable to authenticate to ASP.NET Web Api service with HttpClient)?
推荐答案
您可以通过登录的用户,像这样的电流发送:
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
});
}
}
}
然后要确保在你的控制器每个动作使用[MyAPIAuthorizationFilter]
then use [MyAPIAuthorizationFilter] on each action in your controller that you want to secure.
这篇关于如何验证WPF客户端请求ASP .NET的WebAPI 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!