[英]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.