如何手动设置登录的身份用户
本文关键字:身份 用户 登录 何手动 设置 | 更新日期: 2023-09-27 17:56:59
我正在将 ASP.NET 身份与ADFS服务器一起使用。出于开发目的,我希望避免在无法访问 ADFS 服务器的网络环境中使用 ADFS 服务器。这就是为什么我在主控制器中添加了一个简单的控制器操作,手动设置当前登录的用户:
#if DEBUG
[AllowAnonymous]
public ActionResult LogIn()
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, "tester"));
System.Web.HttpContext.Current.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;
return Redirect("Home/Index");
}
#endif
和欧文配置方法:
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions() { });
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata
});
}
注释掉我使用 WsFederation 身份验证的部分是没有问题的,这样就没有指向我当前 ADFS 服务器的链接。
问题:当我被重定向到"主页/索引"操作(具有"授权"属性)时,ASP.NET 标识无法将我的 ClaimPrincipal 识别为有效登录名,因此我被重定向到"主页/登录"操作,该操作会不断在"主页/登录名"和"主页/索引"之间创建循环。
我的问题:如何使 ASP.NET 接受上面创建的索赔主体作为有效登录?
您的方法有问题 - 未设置 cookie,因此不会在 HTTP 请求中保留用户信息。您的方法仅在单个调用中有效(有用途,但不适合您)
您仍然可以使用 OWIN 中的IAuthenticationManager
来设置 Cookie:
#if DEBUG
[AllowAnonymous]
public ActionResult LogIn()
{
var identity = new ClaimsIdentity("ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
identity.AddClaim(new Claim(ClaimTypes.Name, "Testy McTestface"));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "testUser"));
IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut("ApplicationCookie");
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
return Redirect("Home/Index");
}
#endif
您将需要 nuget 包Microsoft.Owin.Security.Cookies
, Microsoft.Owin.Host.SystemWeb
.在我的博客文章中查看有关使用 AD 进行身份验证的更多说明
您还需要确保CookieAuthenticationMiddleware
配置正确:
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Home/Login"),
Provider = new CookieAuthenticationProvider(),
CookieName = "ApplicationCookie",
CookieHttpOnly = true,
ExpireTimeSpan = TimeSpan.FromHours(1),
});
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata
});
}
特别是对AuthenticationType
值进行身份验证 - 它必须与构造函数中的值匹配ClaimsIdentity
。否则,将无法设置 Cookie,或者您将无法注销。