How to authenticate a WPF client request for ASP.NET WebAPI 2

I just created an ASP.NET MVC 5 Web API project and added an Entity Framework model and other things to make it work with ASP.NET Identity .

enter image description here

Now I need to create a simple authenticated request for the standard method of this API from the WPF Client application.

ASP.NET MVC 5 Web Interface 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 Client 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 to be connecting to the host and I am getting the correct error. This is normal.

The response status code does not indicate success: 401 (unauthorized).

The main problem I'm not sure how to send username and password using WPF Client ...

(Guys, I’m not asking if I need to encrypt it and use Auth Filter to implement API methods. I will do it for sure later ...)

I heard that I need to send the username and password in the header request ... but I do not know how to do this using HttpClient client = new HttpClient();

Thanks for any hint!

PS I replaced HttpClient with WebClient and used Task ( Failed to authenticate with ASP.NET Web Api service using HttpClient )?

+8
c # asp.net-web-api wpf asp.net-mvc-5
source share
1 answer

You can send by the current registered user as follows:

  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] for each action in your controller that you want to protect.

+6
source share

All Articles