Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        public void SignOut(SignOutOption signOutOption)
        {
            var identity = (CustomIdentity)Thread.CurrentPrincipal?.Identity;

            //       var cacheKeyProfile = CacheKeyOption.Profile + "-" + identity.UserId;

            var sessions = _repositorySession.Get().Where(e => e.Creator.Id == identity.UserId).ToList();

            if (sessions.Count > 0)
            {
                foreach (var session in sessions)
                {
                    _repositorySessionHistory.Add(new SessionHistory
                    {
                        Id                   = GuidHelper.NewGuid(),
                        Creator              = session.Creator,
                        CreationTime         = session.CreationTime,
                        LastModificationTime = DateTime.Now,
                        LogoutType           = signOutOption.ToString(),
                    }, true);

                    _repositorySession.Delete(session, true);
                }
            }

            // Kimlik nesnesi boşaltılıp yeniden oluşturuluyor
            identity = new CustomIdentity();
            identity.AddClaims(new[]
            {
                new Claim("UserId", Guid.Empty.ToString()),
                new Claim("Username", string.Empty),
                new Claim("Password", string.Empty),
                new Claim("FirstName", string.Empty),
                new Claim("LastName", string.Empty),
                new Claim("DisplayName", string.Empty),
                new Claim("Email", string.Empty),
                new Claim("LanguageId", Guid.Empty.ToString()),
                new Claim("IsAuthenticated", false.ToString()),
            });

            var principal = new CustomPrincipal(identity);

            // Thread geçerli kimlik bilgisi ayarlanıyor
            Thread.CurrentPrincipal = principal;
            //     _cacheService.Remove(cacheKeyProfile);
        }
Ejemplo n.º 3
0
        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;
        }
Ejemplo n.º 4
0
        public async Task Invoke(HttpContext context)
        {
            var httpContext     = context.Request.HttpContext;
            var securityService = httpContext.RequestServices.GetService <IIdentityService>();

            try
            {
                var identity = securityService.Get();
                if (identity == null)
                {
                    identity = new CustomIdentity();
                    identity.AddClaims(new[]
                    {
                        new Claim("UserId", Guid.Empty.ToString()),
                        new Claim("Username", string.Empty),
                        new Claim("Password", string.Empty),
                        new Claim("FirstName", string.Empty),
                        new Claim("LastName", string.Empty),
                        new Claim("DisplayName", string.Empty),
                        new Claim("Email", string.Empty),
                        new Claim("LanguageId", Guid.Empty.ToString()),
                        new Claim("IsAuthenticated", false.ToString()),
                    });
                }
                var principal = new CustomPrincipal(identity);
                Thread.CurrentPrincipal = principal;
                httpContext.User        = principal;
                var pathValue = httpContext.Request.Path.Value;
                if (pathValue != "/")
                {
                    pathValue = pathValue.Replace("api/", "");

                    var pathValueArray = pathValue.Split('/');

                    if (pathValueArray.Length > 1)
                    {
                        string controller;
                        string action;

                        if (pathValueArray.Length == 2)
                        {
                            controller = pathValueArray[1];
                            action     = "Index";
                        }
                        else
                        {
                            controller = pathValueArray[1];
                            action     = pathValueArray[2];
                        }
                        var mainService = httpContext.RequestServices.GetService <IMainService>();
                        var actionRoles = mainService.GetActionRoles(controller, action);

                        // Sayfa vtde kayıtlı değilse devam et
                        if (actionRoles != null && actionRoles.Count > 0)
                        {
                            var identityIsAuthorized = identity.Roles.Any(r => actionRoles.Contains(r));
                            if (!identityIsAuthorized)
                            {
                                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                                await context.Response.WriteAsync(Messages.DangerNoPermission);

                                return;
                            }
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = StatusCodes.Status403Forbidden;
                        await context.Response.WriteAsync(Messages.DangerNoPermission);

                        return;
                    }
                }
            }
            catch (Exception e)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                await context.Response.WriteAsync(e.Message);

                return;
            }



            await _next(context);
        }
Ejemplo n.º 5
0
        public CustomIdentity Get()
        {
            var identity = new CustomIdentity();

            if (!File.Exists(FileName))
            {
                identity = new CustomIdentity();
                identity.AddClaims(new[]
                {
                    new Claim("UserId", Guid.Empty.ToString()),
                    new Claim("Username", string.Empty),
                    new Claim("Password", string.Empty),
                    new Claim("FirstName", string.Empty),
                    new Claim("LastName", string.Empty),
                    new Claim("DisplayName", string.Empty),
                    new Claim("Email", string.Empty),
                    new Claim("LanguageId", Guid.Empty.ToString()),
                    new Claim("IsAuthenticated", false.ToString()),
                });
                Set(identity, DateTime.Now.AddMinutes(20), false);
                return(identity);
            }



            var text = File.ReadAllText(FileName);
            var jwt  = text.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);
        }