- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
当 api-controller 使用 windows-authentication 时,我的 api Controller 是否有办法获取发起对 api Controller 的调用的帐户的 IIdentity ?
我的“castController.User.Identity”是(类型)WindowsIdentity。但它是“空的”。
空,原样:IsAuthenticated = false,以及一个空的用户名。它不是空的,它是“空的”。
我的“WebTier”是一个使用自定义 AppPool 运行的 IIS 应用程序,运行自定义 AppPool 的 IIdentity 类似于“mydomain\myServiceAccount”。
我试图让“castController.User.Identity.Name”值成为这个服务帐户。
(我猜它可能是任何能够使用有效 Windows 帐户连接到我的 WebApiTier 的客户端,但我提到这一点以防万一它可能会抛出一个奇怪的事件 Spanner )
我的“WebTier”(Mvc 应用程序)有这个方法:
您会注意到我使用 UseDefaultCredentials 的两种方式。 (阿卡,我一直试图弄清楚这一点)
private async Task<HttpResponseMessage> ExecuteProxy(string url)
{
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true
};
handler.PreAuthenticate = true;
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
webRequestHandler.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Identification;
using (var client = new HttpClient(handler)) /* i've tried webRequestHandler too */
{
Uri destinationUri = new Uri("http://localhost/MyVirtualDirectory/api/mycontroller/mymethod");
this.Request.RequestUri = destinationUri;
return await client.SendAsync(this.Request);
}
}
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Windows" />
public MyController : ApiController
{
[ActionName("MyMethod")]
[MyCustomAuthorization]
public IEnumerable<string> MyMethod()
{
return new string[] { "value1", "value2" };
}
}
public class MyCustomAuthorizationAttribute : System.Web.Http.AuthorizeAttribute
{
private string CurrentActionName { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
this.CurrentActionName = actionContext.ActionDescriptor.ActionName;
base.OnAuthorization(actionContext);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var test1 = System.Threading.Thread.CurrentPrincipal;
/* the above is "empty" */
////string userName = actionContext.RequestContext.Principal;/* Web API v2 */
string userName = string.Empty;
ApiController castController = actionContext.ControllerContext.Controller as ApiController;
if (null != castController)
{
userName = castController.User.Identity.Name;
/* the above is "empty" */
}
return true;
}
}
IEnumerable<string> returnItems = null;
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true
};
handler.PreAuthenticate = true;
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.UseDefaultCredentials = true;
webRequestHandler.AllowPipelining = true;
webRequestHandler.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
webRequestHandler.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Identification;
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string serviceUrl = "http://localhost/MyVirtualDirectory/api/mycontroller/mymethod";
HttpResponseMessage response = client.GetAsync(new Uri(serviceUrl)).Result;
var temp1 = (response.ToString());
var temp2 = (response.Content.ReadAsStringAsync().Result);
if (response.IsSuccessStatusCode)
{
Task<IEnumerable<string>> wrap = response.Content.ReadAsAsync<IEnumerable<string>>();
if (null != wrap)
{
returnItems = wrap.Result;
}
else
{
throw new ArgumentNullException("Task<IEnumerable<string>>.Result was null. This was not expected.");
}
}
else
{
throw new HttpRequestException(response.ReasonPhrase + " " + response.RequestMessage);
}
最佳答案
行。我弄清楚了这个问题。感谢这篇文章。
How to get Windows user name when identity impersonate="true" in asp.net?
//开始报价//
与 <authentication mode="Windows"/>
在您的应用程序中并在 IIS 中启用匿名访问,您将看到以下结果:
System.Environment.UserName: Computer Name
Page.User.Identity.Name: Blank
System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
[IdentityWhiteListAuthorization]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
}
namespace WebApiIdentityPoc.Domain
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
//using ProductsApp.Models;
using WebApiIdentityPoc.Domain;
namespace ProductsApp.Controllers
{
public class ProductsController : ApiController
{
System.Net.Http
System.Net.Http.Formatting
System.Net.Http.WebRequest (this one is may not be needed)
namespace WebApiIdentityPoc.ConsoleOne
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WebApiIdentityPoc.Domain;
public class Program
{
private static readonly string WebApiExampleUrl = "http://localhost:47503/api/Products/GetAllProducts"; /* check ProductsApp.csproj properties, "Web" tab, "IIS Express" settings if there is an issue */
public static void Main(string[] args)
{
try
{
System.Security.Principal.WindowsIdentity ident = System.Security.Principal.WindowsIdentity.GetCurrent();
if (null != ident)
{
Console.WriteLine("Will the Identity '{0}' Show up in IdentityWhiteListAuthorizationAttribute ???", ident.Name);
}
RunHttpClientExample();
RunWebClientExample();
RunWebClientWicExample();
}
catch (Exception ex)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
Exception exc = ex;
while (null != exc)
{
sb.Append(exc.GetType().Name + System.Environment.NewLine);
sb.Append(exc.Message + System.Environment.NewLine);
exc = exc.InnerException;
}
Console.WriteLine(sb.ToString());
}
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
}
private static void RunWebClientExample()
{
/* some articles said that HttpClient could not pass over the credentials because of async operations, these were some "experiments" using the older WebClient. Stick with HttpClient if you can */
WebClient webClient = new WebClient();
webClient.UseDefaultCredentials = true;
string serviceUrl = WebApiExampleUrl;
string json = webClient.DownloadString(serviceUrl);
IEnumerable<Product> returnItems = JsonConvert.DeserializeObject<IEnumerable<Product>>(json);
ShowProducts(returnItems);
}
private static void RunWebClientWicExample()
{
/* some articles said that HttpClient could not pass over the credentials because of async operations, these were some "experiments" using the older WebClient. Stick with HttpClient if you can */
System.Security.Principal.WindowsIdentity ident = System.Security.Principal.WindowsIdentity.GetCurrent();
WindowsImpersonationContext wic = ident.Impersonate();
try
{
WebClient webClient = new WebClient();
webClient.UseDefaultCredentials = true;
string serviceUrl = WebApiExampleUrl;
string json = webClient.DownloadString(serviceUrl);
IEnumerable<Product> returnItems = JsonConvert.DeserializeObject<IEnumerable<Product>>(json);
ShowProducts(returnItems);
}
finally
{
wic.Undo();
}
}
private static void RunHttpClientExample()
{
IEnumerable<Product> returnItems = null;
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true, PreAuthenticate = true
};
////////WebRequestHandler webRequestHandler = new WebRequestHandler();
////////webRequestHandler.UseDefaultCredentials = true;
////////webRequestHandler.AllowPipelining = true;
////////webRequestHandler.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
////////webRequestHandler.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Identification;
using (HttpClient client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string serviceUrl = WebApiExampleUrl;
HttpResponseMessage response = client.GetAsync(new Uri(serviceUrl)).Result;
var temp1 = response.ToString();
var temp2 = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Task<IEnumerable<Product>> wrap = response.Content.ReadAsAsync<IEnumerable<Product>>();
if (null != wrap)
{
returnItems = wrap.Result;
}
else
{
throw new ArgumentNullException("Task<IEnumerable<Product>>.Result was null. This was not expected.");
}
}
else
{
throw new HttpRequestException(response.ReasonPhrase + " " + response.RequestMessage);
}
}
ShowProducts(returnItems);
}
private static void ShowProducts(IEnumerable<Product> prods)
{
if (null != prods)
{
foreach (Product p in prods)
{
Console.WriteLine("{0}, {1}, {2}, {3}", p.Id, p.Name, p.Price, p.Category);
}
Console.WriteLine(string.Empty);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace ProductsApp.WebApiExtensions
{
public class IdentityWhiteListAuthorizationAttribute : System.Web.Http.AuthorizeAttribute
{
public IdentityWhiteListAuthorizationAttribute()
{
}
private string CurrentActionName { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
this.CurrentActionName = actionContext.ActionDescriptor.ActionName;
base.OnAuthorization(actionContext);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var test1 = System.Threading.Thread.CurrentPrincipal;
var test2 = System.Security.Principal.WindowsIdentity.GetCurrent();
////string userName = actionContext.RequestContext.Principal.Name;/* Web API v2 */
string dingDingDingUserName = string.Empty;
ApiController castController = actionContext.ControllerContext.Controller as ApiController;
if (null != castController)
{
dingDingDingUserName = castController.User.Identity.Name;
}
string status = string.Empty;
if (string.IsNullOrEmpty(dingDingDingUserName))
{
status = "Not Good. No dingDingDingUserName";
}
else
{
status = "Finally!";
}
return true;
}
}
}
[IdentityWhiteListAuthorization]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
Anonymous Authentication | Enabled
Windows Authentication | Enabled
<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
Anonymous Authentication | Disabled
<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
Anonymous Authentication Enabled/Disabled
Windows Authentication Enabled/Disabled
<sectionGroup name="security">
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
<!-- Other Stuff -->
<section name="windowsAuthentication" overrideModeDefault="Allow" />
</sectionGroup>
<security>
<authentication>
<anonymousAuthentication enabled="true" userName="" />
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>
关于c# - HttpClient 调用 Windows 身份验证 Api Controller 方法...但没有 WindowsIdentity 出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887865/
我正在尝试检查Powerhell脚本是否以管理员身份运行。 在网上搜索后,我得到了一些运行良好的示例代码。 为了获得WindowsPrincipal对象,我发现了以下两个示例代码。 第一: New-O
我正在尝试使用 SID-s 检查用户是否属于某些组。 我正在使用 WindowsIdentity.Groups ,但后来注意到有时它不显示用户属于管理员组。 搜索了一段时间后,我发现不是Windows
我试图拦截 WindowsAuthenticationModule 以另一个用户身份登录到应用程序,但我无法在不知道他的密码的情况下创建新的 WindowsIdentity。该代码将在管理员权限下运行
我正在开发具有以下详细信息的客户端服务器应用程序: Client(C++) -----------HTTPS--- Server (C#/WCF) 服务器: 与 Windows Active
当我像这样使用 WindowsIdentity 模拟时: WindowsIdentity newId = null; WindowsImpersonationContext impe
我正在构建一个站点,该站点使用当前用户的 WindowsIdentity 获取用户信息。我从中获得的主要信息是 ssid。 我按如下方式为当前用户执行此操作 IntPtr logonToken = W
ServiceSecurityContext 为何包含 WindowsIdentity 属性? 即,如果用户使用 Windows 身份验证机制进行身份验证,则 ServiceSecurityConte
获取当前用户的用户名和/或 SID 时,首选方法是什么? 是否使用: WindowsIdentity.GetCurrent().Owner 或者: WindowsIdentity.GetCurrent
我正在尝试在我的 WPF 客户端/服务器 (WCF) 应用程序中使用 Windows Identity Foundation 进行授权,该应用程序可能会或可能不会在与提供身份验证的事件目录相同的信任环
我正在一个安全的服务器上运行一个应用程序(我必须远程访问并且必须通过电子邮件将文件发送给某人以便他们将它们放到服务器上,因此更改代码不是一个快速的过程)。 在某一时刻,该服务通过获取登录用户 Oper
我有一个由 IIS 托管的 Web 应用程序。它配置了表单例份验证和匿名身份验证,并且启用了模拟。应用程序池帐户是网络服务。匿名帐户是 Costa。 Costa 可以访问数据库。 NetworkSer
假设我有一个 WindowsIdentity 的实例,并且想要获取它所属的组。我使用以下代码获取列表: WindowsIdentity identity = null; // get iden
我正在使用模拟在连接到域的 Windows 7 计算机上实例化 WindowsIdentity。我通过 Groups 属性取回了很多组。一些域、本地和内置但我没有得到用户所在的内置管理员组。我很困惑为
我正在使用 WindowsIdentity 获取当前用户的 ID 以执行 SSO。在大多数情况下,我得到的正是我想要的,但对于某些用户来说,我得到的结果很奇怪。示例代码: IIdentity WinI
TL;DR WindowsIdentity 的 Token 属性中是否包含用户 token (例如,someIdentity.Token) 被欺骗: var validated = new Windo
我有以下代码: var baseUrl = "https://" + GetIdentityProviderHost(environment) + "/oauth2/authorize"; var q
我正在使用 Windows 身份验证的 ASP.NET 应用程序中。 我正在使用 HttpContext.Current.User.Identity.Name 获取当前经过身份验证的用户的用户名,这会
我有一个安装项目(在 Windows 7 上运行)在提交时启动自定义操作,启动刚刚安装的应用程序。在此应用程序启动期间,我有一个方法可以检查当前用户名以执行某些身份验证。当从此自定义操作启动时,我得到
如何从收到的msmq消息中获取发件人的WindowsIdentity? 我使用 msmq 作为传输和安全应用程序 block ,并使用授权规则提供程序进行操作授权。我需要 WindowsPrincip
我有一个 ASP.NET 网站,它要求我的应用程序池是经典 .Net 应用程序池。该站点在 IIS 7 上的 .NET 3.5 上运行。当我尝试获取已登录用户的 Active Directory 用户
我是一名优秀的程序员,十分优秀!