IIS可以';t获取已登录的用户

本文关键字:登录 用户 获取 可以 IIS | 更新日期: 2023-09-27 17:59:32

Im使用透明代理将前端传输到后台,但即使激活了角色,也无法获取已登录的用户。

获取透明代理:

    [HttpGet, Route("api/{*url}")]
    public HttpResponseMessage Get(string url)
    {
        var client = new WebClient { UseDefaultCredentials = true };
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
        var result = JsonConvert.DeserializeObject<Object>(Encoding.UTF8.GetString(client.DownloadData(ConfigurationManager.AppSettings["InternalWebApiUrl"] + "/" + url)));
        return Request.CreateResponse(result);
    }

任何获取日志用户的尝试都失败了,我只获取ApplicationalPool用户。

我的尝试:

1-使用IIS配置来激活模拟,并将以下代码添加到webconfig:

 <authorization>
  <allow users ="*" />
 </authorization>

2-创建了一个GetCurrentUser服务来测试传递到后端的凭据,但只有ApplicationalPool用户出现:

    [HttpGet, ResponseType(typeof(string)), Route("GetCurrentUser")]
    public HttpResponseMessage GetCurrentUser()
    {
         WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
        WindowsImpersonationContext ctx = winId.Impersonate();
        var userHTTPContext = HttpContext.Current.User.Identity.Name;
        var userThread = Thread.CurrentPrincipal.Identity.Name;
        var userImpersonated = winId.Name;
        return Request.CreateResponse("HTTP Context: " + userHTTPContext.ToString() + " Thread: " + userThread.ToString() + " Impersonated: " + userImpersonated.ToString());
    }

如何获取已登录的用户
我是否可能通过在WebClient中使用UseDefaultCredentials来传递ApplicationalPool用户?

IIS可以';t获取已登录的用户

原来必须启用SPN(服务主体名称)。

最终代码:

    [Authorize]
    [HttpGet, Route("api/{*url}")]
    public HttpResponseMessage Get(string url)
    {
        WindowsIdentity wi = null;
        wi = (WindowsIdentity)HttpContext.Current.User.Identity;
        using (wi.Impersonate())
        {
            var baseAddress = ConfigurationManager.AppSettings["BaseAddress"] + "/" + url;
            var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
                http.Accept = "application/json; charset=utf-8";
                http.ContentType = "application/json; charset=utf-8";
                http.Method = "GET";
                http.UseDefaultCredentials = true;
                try
                {
                    var response = http.GetResponse();
                    var stream = response.GetResponseStream();
                    var sr = new StreamReader(stream);
                    var contentResponse = sr.ReadToEnd();
                    return Request.CreateResponse(JsonConvert.DeserializeObject<Object>(contentResponse));
                }
                catch (Exception ex)
                {
                     return Request.CreateResponse(HttpStatusCode.BadRequest);
                }
        }
    }