Skip to content

Instantly share code, notes, and snippets.

@jellebens
Created January 28, 2014 08:34
Show Gist options
  • Save jellebens/8664062 to your computer and use it in GitHub Desktop.
Save jellebens/8664062 to your computer and use it in GitHub Desktop.
public class MyAuthenticationManager : ClaimsAuthenticationManager
{
private readonly IWindsorContainer _container;
private readonly ILogger _logger;
public MyAuthenticationManager(IWindsorContainer container)
{
_container = container;
_logger = _container.Resolve<ILoggerFactory>().Create(Loggers.Security);
}
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
_logger.InfoFormat("Logon attempt of {0}", incomingPrincipal.GetUserName());
if (incomingPrincipal != null
&& incomingPrincipal.Identity.IsAuthenticated
&& incomingPrincipal.FindFirst(ClaimTypes.Name) != null)
{
string userName = incomingPrincipal.GetUserName();
var repository = _container.Resolve<IRepository>();
var user = repository.Query<User>()
.SingleOrDefault(u => u.UserName.Equals(userName) && u.IsActive);
user.LastLogin = DateTime.Now;
//User not known in the application
if (user == null)
{
string msg = string.Format("User {0} is not known or no longer active", userName);
_logger.FatalFormat("Logon of user with following username {0} failed with message: {1}", userName, msg);
throw new SecurityException(msg);
}
var identity = ((ClaimsIdentity)incomingPrincipal.Identity);
foreach (Role role in user.Roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role.Code));
}
repository.Commit();
_logger.InfoFormat("Logon of {0} granted", userName);
_container.Release(repository);
}
return incomingPrincipal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment