ASP.NET Web API Self-Host with Windows Authentication

前端 未结 9 1221
不知归路
不知归路 2021-01-30 11:31

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

9条回答
  •  失恋的感觉
    2021-01-30 12:06

    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
    }
    

提交回复
热议问题