After I login in my ASP.NET MVC app, I need somehow to get the current user login name.
My code is like this:
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
});
}
}
My 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;
}
And finally my login action in the controller
[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);
}
The authentication works fine, IsSuccess
returns true.
However I can't get the current user logged in, I have tried:
HttpContext.Current.User
UserPrincipal.Current
etc,etc
And it's always empty.
The question is how to get current user after logged in?
Am I missing something in web.config
? or a misconfiguration on the app pool?