I am trying to use the ASP.NET Web API Self-Host option with Windows authentication so I can determine the logged on user and ultimately accept or reject the user based on their
Related answer for whom need it, about basic auth with token
Merging some help, info, answers and a self auth system that I made for a real Web API I could finally use roles and attributes tags for this. Is made for Authorization tag in the header.
Server invocation:
var config = new HttpSelfHostConfiguration("http://localhost:8080");
config.UserNamePasswordValidator = new PHVValidator();
config.Routes.MapHttpRoute(
"API Default", "{controller}/{id}",
new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DominusForm());
}
Auth Method: (hardcoded for ex. only, choose user, pass and roles from anywhere)
public class PHVValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (userName == "admin" && password == "123")
{
string[] rolarray = new string[] { "admin" };
IPrincipal principal = new GenericPrincipal(new GenericIdentity(userName), rolarray);
Thread.CurrentPrincipal = principal;
}
}
}
Method:
[Authorize(Roles = "admin")]
public HttpResponseMessage Get()
{
do things
}