How to authenticate WPF Client request to ASP .NET WebAPI 2 - c#

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.
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 5 Web 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 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 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).
The main problem that I am not sure how to send username and password using WPF Client...
(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...)
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();
Thanks for any clue!
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
});
}
}
}
then use [MyAPIAuthorizationFilter] on each action in your controller that you want to secure.

Related

.NET 6 API SignInAsync with cookie authentication is not being kept via front-end but works via Swagger

I'm trying to learn how to use authentication and SignInAsync via an API. For some reason, my code works only if I call the API from Postman or from Swagger, but not when I call it from code in the front-end.
To test this, I created two small projects: a web razor pages front end and a simple API. The API has the 3 possible POST requests (TestLogin, TestLogout and TestVerify) as show below:
[Route("api/[controller]")]
[ApiController]
[Authorize()]
public class LoginTestController : ControllerBase
{
[AllowAnonymous]
[HttpPost("TestLogin")]
public async Task<ActionResult> TestLoginAction([FromBody] LoginData loginData)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, loginData.UserName),
new Claim(ClaimTypes.Role, loginData.UserRole)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
if (principal is not null && principal.Identity is not null)
{
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return Ok("Successfully logged in.");
}
else
{
return BadRequest("Login failed.");
}
}
[HttpPost("TestVerify")]
public ActionResult TestVerify()
{
var user = User.Identity;
if (user is not null && user.IsAuthenticated)
return Ok($"Logged in user: " + user.Name);
else
return Ok("No user logged in. Please login.");
}
[HttpPost("TestLogout")]
public async Task<ActionResult> TestLogout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
}
In my Program.cs, I add the cookie authentication
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
and
app.UseAuthentication();
app.UseAuthorization();
In my front-end razor page, I called the APIs this way using this code:
public string Message { get; set; }
public async Task OnPostLogin()
{
var client = new HttpClient();
var userLoginInfo = new LoginData
{
UserName = "TestUser",
UserRole = "TestRole"
};
string api = "https://localhost:7049/api/LoginTest/TestLogin";
var response = await client.PostAsJsonAsync(api, userLoginInfo);
Message = await response.Content.ReadAsStringAsync();
}
public async Task OnPostLogout()
{
var client = new HttpClient();
var userLoginInfo = new LoginData();
string api = "https://localhost:7049/api/LoginTest/TestLogout";
var response = await client.PostAsJsonAsync(api, userLoginInfo);
Message = await response.Content.ReadAsStringAsync();
}
public async Task OnPostValidate()
{
var client = new HttpClient();
var userLoginInfo = new LoginData();
string api = "https://localhost:7049/api/LoginTest/TestVerify";
var response = await client.PostAsJsonAsync(api, userLoginInfo);
int statusCode = ((int)response.StatusCode);
if (response.IsSuccessStatusCode)
Message = await response.Content.ReadAsStringAsync();
else
Message = $"Failed with status code: ({response.StatusCode}/{statusCode})";
}
If I try via the front-end, I click on the Login, and it says it is successfully, but when I click on the Validate, it returns a 404 presumably because it doesn't think it is authorized even though I did a log in (or if I authorize anonymous for the validate, it says no one is logged in). If I do the same calls via Swagger, the login works the same, but the validate remembers the login, which is the desired behavior. Why is the login not being remembered when I call the API via the front-end, but it is when I do it via Swagger? And how can I fix this?
Thanks.

ASP.NET Web API 2 Custom Authorization and Authorize Attribute

I have created a Google Chrome Extension and I plan to communicate with ASP.NET Wep API 2 service. Web service creates encrypted FormsAuthenticationTicket and sends it in the Login/SignIn response for the first time. Validating user whether is authorized or not has been controlled by checking Request Cookie.
Project creates ticket via GetEncryptedTicket(int UserID) function.
How can control and use [Authorize] attribute above the service functions? I know oAuth 2.0 may be the better option to implement it but I want to use following function to create ticket.
public static string GetEncryptedTicket(int UserID)
{
DateTime now = DateTime.UtcNow.ToLocalTime();
var ticket = new FormsAuthenticationTicket(
1,
"TICKET_NAME",
now,
now.Add(FormsAuthentication.Timeout),
true,
UserID.ToString(),
FormsAuthentication.FormsCookiePath
);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
return encryptedTicket;
}
Use Action filter to validate the token like this
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try
{
if (actionContext.Headers.GetValues("UserToken").FirstOrDefault() == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
ReasonPhrase = "Http request doesnot have the UserToken header"
};
}
else
{
string username = string.Empty, password = string.Empty;
var userToken = actionContext.Request.Headers.GetValues("UserToken").FirstOrDefault();
var token = FormsAuthentication.Decrypt(userToken);
if (token.Expired)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
{
ReasonPhrase = "Invalid User Token"
};
}
}
}
catch (Exception ex)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError)
{
ReasonPhrase = ex.Message
};
}
}
}
And Use [BasicAuthentication] Attribute to validate token and allow Access

AuthorizeAttribute & POST Async

I inherited a project that is WEB API in .NET 4.6 framework. It implements custom authentication through the use of System.Web.Http.AuthorizeAttribute such as:
public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//Call authentication logic against DB.
}
}
I myself want to improve this to use the new JWT Token, so I went and wrote a .NET Core project that generates and returns a JWT token upon successful authentication. I tested this piece using Postman to POST to the controller and it works.
Now, in my current code I want to invoke that WEB-API call inside the OnAuthorization() such as follow:
public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var auth = actionContext.Request.Headers.Authorization;
string[] userInfo = Encoding.Default.GetString(Convert.FromBase64String(auth.Parameter)).Split(':');
Profile user = new Profile();
user.UserName = userInfo[0];
user.Password = userInfo[1];
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:31786");
var response = client.PostAsJsonAsync("api/token/request", user);
//I hope to get the JWT Token back here or by this time the server should return it or set it in a cookie.
return "OK";
}
}
But I can't get this to work, the response.Status is returning "WaitingForActivation".
I know why I'm getting this because I should change this call to have await and update the function's signature to Task.
await client.PostAsJsonAsync("api/token", content);
However, I'm not able to do this because of the restriction from System.Web.Http.AuthorizeAttribute. What can I do here, is there a way to still invoke an async call from within here or do I have to move my logic to somewhere else?
That's not a problem if you use the correct overload:
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken token)
{
var auth = actionContext.Request.Headers.Authorization;
string[] userInfo = Encoding.Default.GetString(Convert.FromBase64String(auth.Parameter)).Split(':');
Profile user = new Profile();
user.UserName = userInfo[0];
user.Password = userInfo[1];
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:31786");
var response = await client.PostAsJsonAsync("api/token/request", user);
//I hope to get the JWT Token back here or by this time the server should return it or set it in a cookie.
return "OK";
}
By the way, you should take out that new HttpClient() from there and reuse it instead.

Authenticate users in Asp .net Web API

I'm writing API which will be consumed by mobile devices and I want to secure this API end points.
User authentication details is provide by another application called User Manger API (another project which contains user details).
How to make use of ASP.NET Identity framework Authorization and other features to secure my API endpoints while getting the user data from the User manager API ?
The question is a bit broad; basically you are looking for a strategy to authenticate and authorise a client for a web api (dotnet core or normal framework?) using a different existing API (is that API in your control, can you modify it if needed?)
If you can modify both, id say look through StackOverflow and Google for JWT tokens, OAuth and identity server.
1- you can implement an attribute and decorate your api controller.
2- you can implement and register a global filter inside your asp.net's app_start (and make sure you are registering filters in your global.asax).
3- you can do what #Roel-Abspoel mentions implement Identity Server in your User Manager API and have your client talk to it and get the token, then your API talk to it to validate the token.
There are other ways, but i will keep this short and sweet.
Here is an example using an attribute:
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Filters;
namespace myExample
{
public class ExternalAuthenticationAttribute : IAuthenticationFilter
{
public virtual bool AllowMultiple
{
get { return false; }
}
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
// get request + authorization headers
HttpRequestMessage request = context.Request;
AuthenticationHeaderValue authorization = request.Headers.Authorization;
// check for username and password (regardless if it was validated on the client, server should check)
// this will only accept Basic Authorization
if (String.IsNullOrEmpty(authorization.Parameter) || authorization.Scheme != "Basic")
{
// Authentication was attempted but failed. Set ErrorResult to indicate an error.
context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request);
return null;
}
var userNameAndPasword = GetCredentials(authorization.Parameter);
if (userNameAndPasword == null)
{
// Authentication was attempted but failed. Set ErrorResult to indicate an error.
context.ErrorResult = new AuthenticationFailureResult("Could not get credentials", request);
return null;
}
// now that we have the username + password call User manager API
var client = new HttpClient();
// POST USERNAME + PASSWORD INSIDE BODY, not header, not query string. ALSO USE HTTPS to make sure it is sent encrypted
var response = AuthenticateAgainstUserMapagerApi1(userNameAndPasword, client);
// THIS WILL WORK IN .NET CORE 1.1. ALSO USE HTTPS to make sure it is sent encrypted
//var response = AuthenticateAgainstUserMapagerApi2(client, userNameAndPasword);
// parse response
if (!response.IsSuccessStatusCode)
{
context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request);
}
else
{
var readTask = response.Content.ReadAsStringAsync();
var content = readTask.Result;
context.Principal = GetPrincipal(content); // if User manager API returns a user principal as JSON we would
}
return null;
}
//private static HttpResponseMessage AuthenticateAgainstUserMapagerApi2(HttpClient client, Tuple<string, string> userNameAndPasword)
//{
// client.SetBasicAuthentication(userNameAndPasword.Item1, userNameAndPasword.Item2);
// var responseTask = client.GetAsync("https://your_user_manager_api_URL/api/authenticate");
// return responseTask.Result;
//}
private static HttpResponseMessage AuthenticateAgainstUserMapagerApi1(Tuple<string, string> userNameAndPasword, HttpClient client)
{
var credentials = new
{
Username = userNameAndPasword.Item1,
Password = userNameAndPasword.Item2
};
var responseTask = client.PostAsJsonAsync("https://your_user_manager_api_URL/api/authenticate", credentials);
var response = responseTask.Result;
return response;
}
public IPrincipal GetPrincipal(string principalStr)
{
// deserialize principalStr and return a proper Principal instead of ClaimsPrincipal below
return new ClaimsPrincipal();
}
private static Tuple<string, string> GetCredentials(string authorizationParameter)
{
byte[] credentialBytes;
try
{
credentialBytes = Convert.FromBase64String(authorizationParameter);
}
catch (FormatException)
{
return null;
}
try
{
// make sure you use the proper encoding which match client
var encoding = Encoding.ASCII;
string decodedCredentials;
decodedCredentials = encoding.GetString(credentialBytes);
int colonIndex = decodedCredentials.IndexOf(':');
string userName = decodedCredentials.Substring(0, colonIndex);
string password = decodedCredentials.Substring(colonIndex + 1);
return new Tuple<string, string>(userName, password);
}
catch (Exception ex)
{
return null;
}
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
public class AuthenticationFailureResult : IHttpActionResult
{
public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
{
ReasonPhrase = reasonPhrase;
Request = request;
}
public string ReasonPhrase { get; private set; }
public HttpRequestMessage Request { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Execute());
}
private HttpResponseMessage Execute()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage = Request;
response.ReasonPhrase = ReasonPhrase;
return response;
}
}
}
use the attribute on your API class like this, which will call User Manager API each time PurchaseController is accessed:
[ExternalAuthenticationAttribute]
public class PurchaseController : ApiController

Cannot authenticate in Web API service called from MVC website

I have an ASP.NET MVC website using angular for the front end, that then needs to communicate to a REST Web API service to retrieve data. I have authentication logic against a custom provider in my MVC project and this all works fine using ADLDS. However the calls to the REST Web API have no authentication data passed and I can't work out how to pass the user who is authenticated with MVC, over to the REST Web API.
Here is an example call to the Web API.
public void ApproveModel(int modelVersionId, string comments)
{
var request = new RestRequest("api/modelversion", Method.POST) { RequestFormat = DataFormat.Json };
request.AddBody(new[] { new ModelAction { ModelActionType = ModelActionConstants.ModelActionApproveModel, ActionParameters = new Dictionary<string, string> { { ModelActionConstants.ModelActionParameterModelVersionId, modelVersionId.ToString(CultureInfo.InvariantCulture) }, {ModelActionConstants.ModelActionParameterComments, comments} } } });
request.UseDefaultCredentials = true;
var response = _client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
throw new ServerException(response.Content);
}
My Web API Controller method (abbreviated)
[ValidateAccess(Constants.Dummy, Constants.SECURE_ENVIRONMENT)]
public HttpResponseMessage Post(ModelAction[] actions)
{
...
}
And my custom validate access attribute which uses Thinktecture
public class ValidateAccess : ClaimsAuthorizeAttribute
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ValidateAccess));
private readonly string _resource;
private readonly string _claimsAction;
public ValidateAccess(string claimsAction, string resource)
{
_claimsAction = claimsAction;
_resource = resource;
XmlConfigurator.Configure();
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (actionContext == null) throw new ArgumentNullException("actionContext");
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Log.InfoFormat("User {0} is not authenticated - Not authorizing further. Redirecting to error page.",
HttpContext.Current.User.Identity.Name);
return false;
}
// specified users or roles when we use our attribute
return CheckAccess(actionContext);
}
protected override bool CheckAccess(HttpActionContext actionContext)
{
if (_claimsAction == String.Empty && _resource == string.Empty)
{
//user is in landing page
return true;
}
return ClaimsAuthorization.CheckAccess(_claimsAction, _resource);
}
}
My problems are
I am not familiar with Web Api. Is IsAuthorized(HttpActionContext actionContext) the right method to override to enforce access policy on API calls?
Why am I getting null for the User identity?

Categories