我刚刚创建了一个 ASP .NET MVC 5 Web API 项目,并添加了实体框架模型和其他内容,以使其与ASP. NET Identity一起使用。
现在我需要从WPF客户端应用程序创建一个简单的经过身份验证的API 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();
感谢您的任何线索!
P.S。我是否将HttpClient
替换为WebClient
并使用Task
(Unable to authenticate to ASP.NET Web Api service with HttpClient)?
答案 0 :(得分:7)
您可以发送当前登录的用户,如下所示:
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]。