登录ASP.NET MVC应用程序后,我需要以某种方式获取当前用户登录名。
我的代码是这样的:
Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
Startup.Auth.cs
public static class ComisionesAuthentication
{
public const String ApplicationCookie = "xyzAuthenticationType";
}
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = ComisionesAuthentication.ApplicationCookie,
LoginPath = new PathString("/Login"),
Provider = new CookieAuthenticationProvider(),
CookieName = "xyzCookie",
CookieHttpOnly = true,
ExpireTimeSpan = TimeSpan.FromHours(12), // adjust to your needs
});
}
}
我的AdAuthservice.cs
public class AdAuthenticationService
{
public class AuthenticationResult
{
public AuthenticationResult(string errorMessage = null)
{
ErrorMessage = errorMessage;
}
public String ErrorMessage { get; private set; }
public Boolean IsSuccess => String.IsNullOrEmpty(ErrorMessage);
}
private readonly IAuthenticationManager authenticationManager;
public AdAuthenticationService(IAuthenticationManager authenticationManager)
{
this.authenticationManager = authenticationManager;
}
/// <summary>
/// Check if username and password matches existing account in AD.
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public AuthenticationResult SignIn(String username, String password)
{
//ContextType authenticationType = ContextType.Domain;
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
bool isAuthenticated = false;
UserPrincipal userPrincipal = null;
bool val = false;
try
{
isAuthenticated = principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate);
if (isAuthenticated)
{
userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
}
}
catch (Exception)
{
isAuthenticated = false;
userPrincipal = null;
}
if (!isAuthenticated || userPrincipal == null)
{
return new AuthenticationResult("Usuario o contraseña incorrecta");
}
else
{
var groups = userPrincipal.GetGroups();
foreach (var item in groups)
{
if (item.Name == "AdminC" || item.Name == "ProovedorC")
val = true;
}
}
if (!val)
{
return new AuthenticationResult("No posees permisos para esta aplicación");
}
if (userPrincipal.IsAccountLockedOut())
{
// here can be a security related discussion weather it is worth
// revealing this information
return new AuthenticationResult("Su cuennta esta bloqueda, contacte un administrador.");
}
if (userPrincipal.Enabled.HasValue && userPrincipal.Enabled.Value == false)
{
// here can be a security related discussion weather it is worth
// revealing this information
return new AuthenticationResult("Su cuenta esta deshabilitada");
}
var identity = CreateIdentity(userPrincipal);
authenticationManager.SignOut(ComisionesAuthentication.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
//UserPrincipal.Current.Name
//HttpContext.Current.User.Identity.Name
//HttpContext.Current.Session.Add("identity", identity);
return new AuthenticationResult();
}
private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal)
{
var identity = new ClaimsIdentity(ComisionesAuthentication.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, userPrincipal.SamAccountName));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName));
if (!String.IsNullOrEmpty(userPrincipal.EmailAddress))
{
identity.AddClaim(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress));
}
// add your own claims if you need to add more information stored on the cookie
return identity;
}
最后我在控制器中的登录操作
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public virtual ActionResult Index(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// usually this will be injected via DI. but creating this manually now for brevity
IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
var authService = new AdAuthenticationService(authenticationManager);
var authenticationResult = authService.SignIn(model.Username, model.Password);
if (authenticationResult.IsSuccess)
{
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", authenticationResult.ErrorMessage);
return View(model);
}
身份验证正常,IsSuccess
返回true。
但是我无法让当前用户登录,我尝试过:
HttpContext.Current.User
UserPrincipal.Current
等,等
而且它总是空着的。
问题是登录后如何获得当前用户?
我错过了web.config
中的内容吗?或者应用程序池上的配置错误?