public CustomIdentity Get() { var identity = new CustomIdentity(); string authorization = Context.Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authorization)) { return(null); } var jwt = authorization.Replace("Bearer ", ""); var takenHeader = Encoding.UTF8.GetString(Convert.FromBase64String(jwt.Split('.')[0])); var takenPayload = Encoding.UTF8.GetString(Convert.FromBase64String(jwt.Split('.')[1])); var takenSignature = Encoding.UTF8.GetString(Convert.FromBase64String(jwt.Split('.')[2])); var newFirstSection = Convert.ToBase64String(Encoding.UTF8.GetBytes(takenHeader)) + "." + Convert.ToBase64String(Encoding.UTF8.GetBytes(takenPayload)); var newSignature = Encoding.UTF8.GetString(Convert.FromBase64String(SecurityHelper.ToHmacSha256(newFirstSection, _key))); if (takenSignature != newSignature) { return(identity); } dynamic jObject = JObject.Parse(takenPayload); Guid userId = jObject.UserId; string username = jObject.Username; string firstName = jObject.FirstName; string lastName = jObject.LastName; string displayName = jObject.DisplayName; string email = jObject.Email; Guid languageId = jObject.LanguageId; JArray roles = jObject.Roles; var claims = new List <Claim> { new Claim("UserId", userId.ToString()), new Claim("Username", username), new Claim("FirstName", firstName), new Claim("LastName", lastName), new Claim("DisplayName", displayName), new Claim("Email", email), new Claim("LanguageId", languageId.ToString()), new Claim("IsAuthenticated", "true", ClaimValueTypes.Boolean), }; identity.AddClaims(claims); foreach (var role in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString())); } return(identity); }
public void Login(LoginModel model) { IValidator validator = new FluentValidator <LoginModel, LoginModelValidationRules>(model); var validationResults = validator.Validate(); if (!validator.IsValid) { throw new ValidationException(Messages.DangerInvalidEntitiy) { ValidationResult = validationResults }; } var user = _repositoryUser .Join(x => x.Language) .Join(x => x.Person) .Join(x => x.Creator) .Join(x => x.RoleUserLines) .ThenJoin(x => x.Role) .Join(x => x.SessionsCreatedBy) .FirstOrDefault(x => x.Username == model.Username); // Kullanıcı sistemde kayıtlı değilse if (user == null) { throw new NotFoundException(Messages.DangerUserNotFound); } // Şifresi yanlış ise if (model.Password.ToSha512() != user.Password) { throw new NotFoundException(Messages.DangerIncorrectPassword); } // Kullanıcı pasif durumda ise if (!user.IsApproved) { throw new NotApprovedException(Messages.DangerItemNotApproved); } // Kullanıcının hiç rolü yoksa if (user.RoleUserLines.Count <= 0) { throw new NotApprovedException(Messages.DangerUserHasNoRole); } var sessionIdList = new List <Guid>(); // Açık kalan oturumu varsa if (user.SessionsCreatedBy?.Count > 0) { foreach (var session in user.SessionsCreatedBy) { // oturum bilgileri tarihçe tablosuna alınıyor _repositorySessionHistory.Add(new SessionHistory { Id = GuidHelper.NewGuid(), Creator = session.Creator, CreationTime = session.CreationTime, LastModificationTime = DateTime.Now, LogoutType = SignOutOption.InvalidLogout.ToString() }, true); sessionIdList.Add(session.Id); } } // Oturumlar siliniyor foreach (var i in sessionIdList) { _repositorySession.Delete(_repositorySession.Get(e => e.Id == i), true); } // Yeni oturum kaydı yapılıyor _repositorySession.Add(new Session { Id = GuidHelper.NewGuid(), Creator = user, CreationTime = DateTime.Now }, true); var roles = user.RoleUserLines .Select( line => _repositoryRoleUserLine .Join(t => t.Role) .FirstOrDefault(x => x.Id == line.Id).Role) .Select(role => new KeyValuePair <Guid, string>(role.Id, role.Name)).ToList(); // Kimlik nesnesi var identity = new CustomIdentity(); // Kullanıcıdaki bilgiler kullanılarak kimlik nesnesinin claim (hak) listesi ayarlanıyor var claims = new List <Claim> { new Claim("UserId", user.Id.ToString()), new Claim("Username", user.Username), new Claim("FirstName", user.Person.FirstName), new Claim("LastName", user.Person.LastName), new Claim("DisplayName", user.Person.DisplayName), new Claim("Email", user.Email), new Claim("LanguageId", user.Language.Id.ToString()), new Claim("IsAuthenticated", "true", ClaimValueTypes.Boolean), new Claim("AuthenticationType", "Normal") }; // claim listesi kimlik nesnesine ekleniyor. identity.AddClaims(claims); // Kullanıcının rol id'leri kimlik nesnesine ekleniyor. foreach (var role in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role.Key.ToString())); } // Yetkilendirilme işlemleri için temel nesne oluşturuluyor var principal = new CustomPrincipal(identity); // Thread geçerli kimlik bilgisi ayarlanıyor Thread.CurrentPrincipal = principal; }