/// <summary>
 /// Returns an instance of a CustomIdentity class, 
 /// given an encrypted authentication string obtained from an HTTP cookie.
 /// </summary>
 /// <param name="encryptedInput">Encrypted string conataining User Identity</param>
 /// <returns>CustomIdentity object</returns>
 public static CustomIdentity Decrypt(string encryptedInput)
 {
     CustomIdentity identity = null;
     try
     {
         string decryptedString = CustomEncryption.Decrypt(encryptedInput);
         //string[] userProperties = decryptedString.Split(new char[] {'|'});
         ArrayList userProperties = new ArrayList();
         Split("|$|", decryptedString, userProperties);
         if(userProperties != null && userProperties.Count > 0)
         {
             identity = new CustomIdentity();
             Type t_identity = identity.GetType();
             PropertyInfo[] propertyInfo = t_identity.GetProperties();
             for( int i = 0; i < propertyInfo.Length; i++)
             {
                 PropertyInfo property = propertyInfo[i];
                 if(property.CanWrite)
                 {
                     string propertyValue = userProperties[i].ToString();
                     object objValue = Convert.ChangeType(propertyValue, property.PropertyType);
                     property.SetValue(identity, objValue, null);
                 }
             }
         }
     }
     catch(Exception e)
     {
         string str = e.Message;
         throw ;
     }
     return identity;
 }
示例#2
0
        private void Button1_Click(object sender, System.EventArgs e)
        {
            //Write your own Authentication logic here
            if(this.username.Text != "" && this.password.Text !="")
            {
                //Write your own code to get the User Roles
                ArrayList roles = new ArrayList();
                roles.Add("Manager");
                if(this.username.Text == "superuser")
                    roles.Add("Administrator");

                roles.Add("ITUser");

                //Convert roles into pipe "|" separated string
                System.Text.StringBuilder strRoles = new System.Text.StringBuilder();
                foreach(string role in roles)
                {
                    strRoles.Append(role);
                    strRoles.Append("|");
                }

                CustomIdentity userIdentity = new CustomIdentity(this.username.Text, 1, true,
                    true, this.username.Text, "*****@*****.**", strRoles.ToString());

                CustomPrincipal principal = new CustomPrincipal(userIdentity, roles);
                Context.User = principal;
                //string estr = CustomAuthentication.Encrypt(userIdentity);
                CustomAuthentication.RedirectFromLoginPage(userIdentity);
            }
        }
        private static void OnAuthenticateRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication) sender;

            var context = application.Context;

            if (context.User != null && context.User.Identity.IsAuthenticated)
                return;

            var cookieName = FormsAuthentication.FormsCookieName;

            var cookie = application.Request.Cookies[cookieName.ToUpper()];

            if (cookie == null)
                return;
            try
            {
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                var identity = new CustomIdentity(AccountEntry.Deserialize(ticket.UserData), ticket.Name);
                var principal = new GenericPrincipal(identity, identity.GetRoles());
                context.User = principal;
                Thread.CurrentPrincipal = principal;
            }
            catch
            {
            }
        }
示例#4
0
        public CustomPrincipal ConstructCustomPrincipal(IIdentity idIdentity)
        {
            User user = _userRepository.GetByUsername(idIdentity.Name);//FirstOrDefault(n => n.Username == idIdentity.Name &&( n.UserType == UserType.HQAdmin||n.UserType==UserType.SalesRep) );

            if (user == null)
                return null;

            var customIdentity = new CustomIdentity(user.Username, idIdentity.IsAuthenticated, idIdentity.AuthenticationType);

            //foreach (var r in user.UserRoles)
            customIdentity.Roles.Add("ROLE_ADMIN");

            return new CustomPrincipal(customIdentity);
        }
        public void New_Test()
        {
            var user = new User();
            var customIdentity = new CustomIdentity<User>(user, user.Name, true);

            Assert.AreSame(user, customIdentity.Reference);
            Assert.AreEqual("Custom", customIdentity.AuthenticationType);
            Assert.AreEqual(user.Name, customIdentity.Name);

            Assert.IsTrue(customIdentity.IsAuthenticated);

            Assert.Throws<ArgumentNullException>(() => new CustomIdentity<User>(null, "bob", true));
            Assert.Throws<ArgumentException>(() => new CustomIdentity<User>(user, "   ", true));
        }
示例#6
0
        public CustomPrincipal ConstructAgriCustomPrincipal(IIdentity identity)
        {
            User user = _userRepository.ConstructAgriCustomPrincipal(identity.Name);

            if (user == null)
                return null;

            var customIdentity = new CustomIdentity(user.Username, identity.IsAuthenticated, identity.AuthenticationType,user.UserType,null);

            foreach (var r in user.UserRoles)
                customIdentity.Roles.Add(r.ToString());

            return new CustomPrincipal(customIdentity);
        }
        public void New_Test()
        {
            var user = new User();
            var identity = new CustomIdentity<User>(user, user.Name, true);
            var roleProvider = new BasicRoleProvider<User>();
            var principal = new CustomPrincipal<User>(identity, roleProvider);
            
            Assert.AreSame(identity, principal.Identity);
            Assert.AreSame(roleProvider, principal.RoleProvider);
            Assert.IsTrue(principal.IsInRole("any string"));

            Assert.Throws<ArgumentNullException>(() => new CustomPrincipal<User>(null, roleProvider));
            Assert.Throws<ArgumentNullException>(() => new CustomPrincipal<User>(identity, null));
        }
示例#8
0
        public CustomPrincipal ConstructCustomPrincipal(IIdentity idIdentity)
        {
            User user = _userRepository.ConstructCustomPrincipal(idIdentity.Name);//FirstOrDefault(n => n.Username == idIdentity.Name &&( n.UserType == UserType.HQAdmin||n.UserType==UserType.SalesRep) );

            if (user == null)
                return null;
            Guid? supplerid = user.Supplier!=null?user.Supplier.Id:(Guid?) null;
            var customIdentity = new CustomIdentity(user.Username, idIdentity.IsAuthenticated, idIdentity.AuthenticationType, user.UserType, supplerid);

            foreach (var r in user.UserRoles)
                customIdentity.Roles.Add(r);
         

            return new CustomPrincipal(customIdentity);
        }
 private static void CheckToken(string token, out bool valid)
 {
     valid = false;
     try
     {
         var bpath = Convert.FromBase64String(token);
         token = System.Text.Encoding.Default.GetString(bpath);
         var jsonStr = "{'" + token.Replace("&", "','").Replace("=", "':'") + "'}";
         var serializer = new JavaScriptSerializer();
         var objs = serializer.Deserialize<TokenModel>(jsonStr);
         using (var accountService = DependencyResolver.Current.GetService<IAccountService>())
         {
             var user = accountService.GetAccounts().FirstOrDefault(n => n.AppId == objs.appid && n.IsDeleted == false);
             if (user == null) return;
             var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
             var timestamp = (int)(DateTime.Now - startTime).TotalSeconds;
             for (var i = 0; i < 600; i++)
             {
                 var signature = SHA1_Hash(string.Format("appsecret={0}&random={1}&timestamp={2}", user.AppSecret, objs.random, timestamp - i));
                 if (objs.signature.ToUpper() == signature)
                 {
                     valid = true;
                     break;
                 }
             }
             if (!valid) return;
             var identity = new CustomIdentity(user);
             var principal = new CustomPrincipal(identity);
             HttpContext.Current.User = principal;
             //得到token 如果超时则重新获取
             if (user.GetAccessTokenDateTime == null || DateTime.Now.Subtract(user.GetAccessTokenDateTime.Value).Duration().TotalSeconds > 7000)
             {
                 var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", user.AppId, user.AppSecret);
                 var accessToken = JsonConvert.DeserializeObject<AccessToken>(HttpGet(url)).access_token;
                 user.GetAccessTokenDateTime = DateTime.Now;
                 user.AccessToken = accessToken;
                 accountService.Update();
             }
         }
     }
     catch (Exception)
     {
         valid = false;
     }
 }
        public void SignIn(User user, bool createPersistentCookie)
        {
            var accountEntry = new AccountEntry(user);

            var authTicket = new FormsAuthenticationTicket(1,
                                                           user.Login,
                                                           DateTime.Now,
                                                           DateTime.Now.AddMinutes(45),
                                                           createPersistentCookie,
                                                           accountEntry.Serialize());

            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
                                 {
                                     Expires = DateTime.Now.Add(FormsAuthentication.Timeout),
                                 };

            HttpContext.Current.Response.Cookies.Add(authCookie);

            var identity = new CustomIdentity(accountEntry, authTicket.Name);

            HttpContext.Current.User = new GenericPrincipal(identity, identity.GetRoles());
        }
        public void SignIn(FormsUser formsUser, bool createPersistentCookie)
        {
            var accountEntry = new AccountEntry(formsUser);

            var authTicket = new FormsAuthenticationTicket(1,
                                                           accountEntry.Id.ToString(),
                                                           DateTime.Now,
                                                           DateTime.Now.AddMinutes(45),
                                                           createPersistentCookie,
                                                           accountEntry.Serialize());

            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName.ToUpper(), encryptedTicket)
            {
                Expires = DateTime.Now.Add(FormsAuthentication.Timeout),
            };

            HttpContext.Current.Response.Cookies.Add(authCookie);

            var identity = new CustomIdentity(authTicket.Name);

            HttpContext.Current.User = new GenericPrincipal(identity, Enumerable.Empty<string>().ToArray());
        }
 private CustomPrincipal(CustomIdentity identity)
     : base(identity)
 {
 }
示例#13
0
        private void VarifyUser(UserLoginResult result)
        {
            if (result.Parameter.ServerName == "")
            {
                result.Message = "Please input the server name.";
                return;
            }
            string serverUrl = string.Empty;

            if (result.Parameter.ServiceName != "")
            {
                serverUrl = result.Parameter.ServerName + "/" + result.Parameter.ServiceName;
            }
            else
            {
                serverUrl = result.Parameter.ServerName;
            }
            serverUrl = AppandProtocal(serverUrl);
            Uri serverUri;

            if (!Uri.TryCreate(serverUrl, UriKind.Absolute, out serverUri))
            {
                result.Message = "The server or service you entered is incorrect.";
                return;
            }
            bool isServerReachable = CheckConnection(serverUri);

            if (!isServerReachable)
            {
                result.Message = "The server or service you entered is not available.";
                return;
            }

            string loginPageUrl      = serverUrl + (serverUrl.EndsWith("/") ? "" : "/") + "Login.aspx";
            bool   isLogiPageAvaible = IsUrlReachable(loginPageUrl);

            if (!isLogiPageAvaible)
            {
                result.Message = "The server or service you entered is not available.";
                return;
            }


            UpdateSetting(ServerUrlSettingName, serverUrl);

            //LoadMetadata();

            string userName = result.Parameter.UserName;
            string password = result.Parameter.Password;
            var    provider = (ClientFormsAuthenticationMembershipProvider)Membership.Provider;

            provider.ServiceUri = ConfigurationManager.AppSettings["ServerUrl"] + "/Authentication_JSON_AppService.axd";
            try
            {
                if (!Membership.ValidateUser(userName, password))
                {
                    result.Message = "The username or password you entered is incorrect.";
                    return;
                }


                IObjectSpace     objectSpace    = new ODataObjectSpace();
                CriteriaOperator userNameFilter = new BinaryOperator("UserName", userName);
                var user =
                    objectSpace.GetObjects("User", userNameFilter, null)._First();

                var userId       = (Guid)user.GetType().GetProperty("UserId").GetValue(user, null);
                var fullName     = (string)user.GetType().GetProperty("FullName").GetValue(user, null);
                var extraColumns = new Dictionary <string, string> {
                    { "Role", "Role" }
                };
                var         userRoles      = objectSpace.GetObjects("UserRole", new BinaryOperator("UserId", userId), extraColumns);
                var         currentRoles   = userRoles.AsQueryable().Select("Role").ToArrayList();
                var         userPrivileges = new List <Privilege>();
                List <Guid> roleIds        = new List <Guid>();
                foreach (var roleObject in currentRoles)
                {
                    var role = (Katrin.Domain.Impl.Role)roleObject;
                    if (!roleIds.Contains(role.RoleId))
                    {
                        roleIds.Add(role.RoleId);
                    }
                    else
                    {
                        continue;
                    }
                    objectSpace.LoadProperty(role, "RolePrivileges");

                    var rolePrivileges = role.RolePrivileges;
                    foreach (var rolePrivilege in rolePrivileges)
                    {
                        objectSpace.LoadProperty(rolePrivilege, "Privilege");
                        var privilege = rolePrivilege.Privilege;
                        var name      = (string)privilege.Name;
                        objectSpace.LoadProperty(privilege, "PrivilegeEntities");
                        var privilegeEntities = privilege.PrivilegeEntities;
                        userPrivileges.AddRange(from object privilegeEntity in privilegeEntities
                                                select(string) privilegeEntity.GetType().GetProperty("EntityName")
                                                .GetValue(privilegeEntity, null)
                                                into entityName
                                                select new Privilege()
                        {
                            EntityName = entityName, Name = name
                        });
                    }
                }

                var identity  = new CustomIdentity(userId, userName, fullName);
                var principal = new CustomPrincipal(identity, userPrivileges.ToArray());
                AppDomain.CurrentDomain.SetThreadPrincipal(principal);
                result.Result = true;
                _loginSuccess = true;
            }
            catch (ThreadAbortException)
            {
                //There just catch the abort exception and then leave this catch block.
            }
            catch (Exception ex)
            {
                //result.Message = BuildExceptionString(ex);
                result.Message = ex.Message;
                MessageService.ShowException(ex);
            }
        }
 public CustomPrincipal(CustomIdentity identity)
 {
     this.Identity = identity;
 }
 public CustomPrincipal(CustomIdentity identity)
 {
     Identity = identity;
 }
示例#16
0
        public ActionResult Index()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(AccessDeniedView());
            }

            identity = ((CustomPrincipal)User).CustomIdentity;


            List <BrnKpi> kpirow = new List <BrnKpi>();

            _permissionservice = new PermissionsService(identity.Name, identity.UserRoleId);

            string[] curBranchList = dashdata.CM_BRANCH.Select(x => x.BRANCH_ID).ToArray(); //.Where(a => a.BRANCH_ID == identity.BranchId);

            if (_permissionservice.IsLevel(AuthorizationLevel.Enterprise))
            {
                curBranchList = curBranchList;
            }
            else if (_permissionservice.IsLevel(AuthorizationLevel.Regional))
            {
                curBranchList = dashdata.CM_BRANCH.Where(a => a.REGION_ID == identity.RegionId).Select(x => x.BRANCH_ID).ToArray();
            }
            else if (_permissionservice.IsLevel(AuthorizationLevel.Zonal))
            {
                curBranchList = dashdata.CM_BRANCH.Where(a => a.ZONECODE == identity.ZoneId).Select(x => x.BRANCH_ID).ToArray();
            }
            else if (_permissionservice.IsLevel(AuthorizationLevel.Branch))
            {
                curBranchList = dashdata.CM_BRANCH.Where(a => a.BRANCH_ID == identity.BranchId).Select(x => x.BRANCH_ID).ToArray();;
            }
            else
            {
                curBranchList = dashdata.CM_BRANCH.Where(a => a.BRANCH_ID == "-1").Select(x => x.BRANCH_ID).ToArray();
            }



            kpirow = _kpidac.GetMultipleBrnKPI(DateTime.Now, curBranchList);
            //using (AppDbContext ctx = new AppDbContext())
            //{
            //    /*
            //    OracleParameter brnParameter = new OracleParameter();
            //    brnParameter.ParameterName = "var_p_branch_code";
            //    brnParameter.Direction = ParameterDirection.Input;
            //    brnParameter.OracleDbType = OracleDbType.Varchar2;

            //    OracleParameter cursorParameter = new OracleParameter();
            //    cursorParameter.ParameterName = "var_p_result";
            //    cursorParameter.Direction = ParameterDirection.Output;
            //    cursorParameter.OracleDbType = OracleDbType.RefCursor; */
            //    object[] prm = new object[] {
            //    new OracleParameter(":var_p_branch_code", OracleDbType.Varchar2, ParameterDirection.Input).Value = identity.BranchId,
            //    new OracleParameter(":var_p_result", OracleDbType.RefCursor, ParameterDirection.Output)
            //    };


            //    List<BrnKpi> kpi = ctx.Database.SqlQuery<BrnKpi>(" exec cmdm_kpi.prc_get_brn_kpi :var_p_branch_code :var_p_result", prm ).ToList();
            //    kpirow = kpi.FirstOrDefault();
            //       //  CommandType.StoredProcedure, cursorParameter);
            //}
            if (kpirow != null)
            {
                ViewBag.allkpi = kpirow;
                //ViewBag.openbrnExceptions = kpirow[0].BRN_OPEN_EXCEPTIONS.ToString("##,##");
                //ViewBag.openbrnExceptions1 = kpirow[1].BRN_OPEN_EXCEPTIONS.ToString("##,##");
                //ViewBag.openbrnExceptions2 = kpirow[2].BRN_OPEN_EXCEPTIONS.ToString("##,##");
                //ViewBag.openbrnExceptions3 = kpirow[3].BRN_OPEN_EXCEPTIONS.ToString("##,##");

                //ViewBag.brnPct = kpirow[kpirow.Count].BRN_PCT_CONTRIB;
                //ViewBag.brnDQI = kpirow[kpirow.Count].BRN_DQI;
                //ViewBag.brnCustomers = kpirow[kpirow.Count].BRN_CUST_COUNT.ToString("##,##");
                //ViewBag.recurringExption = kpirow[kpirow.Count].BRN_RECURRING_ERRORS;
                //ViewBag.bankCustomers = kpirow[kpirow.Count].BANK_CUST_COUNT.ToString("##,##");
            }

            /*
             * int statusCode = (int)IssueStatus.Open;
             * //int openbrnExceptions = dashdata.MdmDqRunExceptions.Where(a=>a.BRANCH_CODE == identity.BranchId && a.ISSUE_STATUS == statusCode).Count();
             * int openbrnExceptions = 1;
             *  //_dqQueService.GetAllBrnQueIssues("", null, identity.BranchId, IssueStatus.Open, null,
             * //0, int.MaxValue, "").Count;
             * ViewBag.openbrnExceptions = openbrnExceptions;
             * int totalExceptions = dashdata.MdmDqRunExceptions.Where(a => a.ISSUE_STATUS == statusCode).Count();
             * //_dqQueService.GetAllBrnQueIssues("", null, null, IssueStatus.Open, null,
             * // 0, int.MaxValue, "").Count;
             * // decimal brnPct = openbrnExceptions/totalExceptions * 100;
             * decimal brnPct = 1;
             * ViewBag.brnPct = brnPct;
             * //
             *
             * decimal brnDQI = dashdata.BranchDqiSummaries
             *  .Where(a => a.BRANCH_CODE == identity.BranchId)
             *  .Select(a => a.DQI)
             *  .Average();// FirstOrDefault();
             * //
             * //.SingleOrDefault();
             * ViewBag.brnDQI = brnDQI;
             * string brnString = identity.BranchId.ToString();
             * int brnCustomers = dashdata.CDMA_INDIVIDUAL_BIO_DATA.Where(a => a.BRANCH_CODE == brnString).Count();
             * int bankCustomers = dashdata.CDMA_INDIVIDUAL_BIO_DATA.Count();
             * ViewBag.brnCustomers = brnCustomers.ToString("##,##");
             * ViewBag.bankCustomers = bankCustomers.ToString("##,##");
             *
             * int unAuthorized = dashdata.CDMA_INDIVIDUAL_BIO_DATA.Where(a => a.BRANCH_CODE == brnString && a.AUTHORISED == "U").Count();
             * ViewBag.unAuthorized = unAuthorized;
             *
             * int recurringExption = 0;
             * ViewBag.recurringExption = recurringExption;
             */
            //int bankCustomers = dashdata.CDMA_INDIVIDUAL_BIO_DATA.Count();
            //ViewBag.bankCustomers = bankCustomers.ToString("##,##");
            int unAuthorized = dashdata.CDMA_INDIVIDUAL_BIO_DATA.Where(a => a.BRANCH_CODE == identity.BranchId && a.AUTHORISED == "U").Count();

            ViewBag.unAuthorized = unAuthorized;
            return(View());
        }
示例#17
0
 public static CustomPrincipal FromIdentity(String identityName, String authenticationType, String[] roles)
 {
     CustomIdentity identity = new CustomIdentity(identityName, authenticationType);
     return new CustomPrincipal(identity, roles);
 }
示例#18
0
        private static void ManualObjectLoad()
        {
            long start, end, freq;
            QueryPerformanceFrequency(out freq);
            QueryPerformanceCounter(out start);
            List<CustomIdentity> identities = new List<CustomIdentity>();
            using (MySqlConnection conn = new MySqlConnection("server=localhost;user id=root;password=pa$$w0rd;database=identitystream;"))
            {

                conn.Open();
                string getCommand = "SELECT * FROM identities";
                MySqlCommand com = new MySqlCommand(getCommand, conn);

                try
                {
                    MySqlDataReader reader = com.ExecuteReader();

                    while (reader.Read())
                    {
                        CustomIdentity iden = new CustomIdentity();
                        iden.Id = reader.GetInt32("id");
                        iden.FirstName = reader.GetString("first_name");
                        iden.LastName = reader.GetString("last_name");
                        iden.CountryCode = reader.GetString("country_code");
                        iden.Active = reader.GetInt32("active");
                        iden.BioEnabled = reader.GetInt32("bio_enabled");
                        iden.IdentityCode = reader.GetString("identity_code");
                        //iden.T24Id = reader.GetString("t24_id");
                        identities.Add(iden);
                    }
                }
                catch (DbException ex)
                {
                    Console.WriteLine(ex.Message);
                }

                conn.Close();
            }
            Console.WriteLine("Loaded Identities");
            QueryPerformanceCounter(out end);
            Console.WriteLine(string.Format("Execution time: {0}", (double)((end - start) / (double)freq) * 1000));
        }
        public ActionResult List()
        {
            var model = new AccountOfficerModel();

            if (!User.Identity.IsAuthenticated)
            {
                return(AccessDeniedView());
            }

            identity           = ((CustomPrincipal)User).CustomIdentity;
            _permissionservice = new PermissionsService(identity.Name, identity.UserRoleId);

            IQueryable <CM_BRANCH> curBranchList = db.CM_BRANCH.OrderBy(x => x.BRANCH_NAME); //.Where(a => a.BRANCH_ID == identity.BranchId);

            if (_permissionservice.IsLevel(AuthorizationLevel.Enterprise))
            {
            }
            else if (_permissionservice.IsLevel(AuthorizationLevel.Regional))
            {
                curBranchList = curBranchList.Where(a => a.REGION_ID == identity.RegionId);
            }
            else if (_permissionservice.IsLevel(AuthorizationLevel.Zonal))
            {
                curBranchList = curBranchList.Where(a => a.ZONECODE == identity.ZoneId).OrderBy(a => a.BRANCH_NAME);
            }
            else if (_permissionservice.IsLevel(AuthorizationLevel.Branch))
            {
                curBranchList = curBranchList.Where(a => a.BRANCH_ID == identity.BranchId).OrderBy(a => a.BRANCH_NAME);
            }
            else
            {
                curBranchList = curBranchList.Where(a => a.BRANCH_ID == "-1");
            }

            model.Branches = new SelectList(curBranchList, "BRANCH_ID", "BRANCH_NAME").ToList();


            if (_permissionservice.IsLevel(AuthorizationLevel.Enterprise))
            {
                model.Branches.Add(new SelectListItem
                {
                    Value    = "0",
                    Text     = "All",
                    Selected = true
                });
            }

            model.AccountOfficers.Add(new SelectListItem
            {
                Value = "2",
                Text  = "Vacant"
            });

            model.AccountOfficers.Add(new SelectListItem
            {
                Value = "1",
                Text  = "None"
            });

            model.AccountOfficers.Add(new SelectListItem
            {
                Value    = "0",
                Text     = "All",
                Selected = true
            });

            _messagingService.SaveUserActivity(identity.ProfileId, "Viewed Account With No AO Codes Report", DateTime.Now);

            return(View(model));
        }
示例#20
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);
        }
示例#21
0
        /// <summary>
        /// Redirects an authenticated user back to the originally requested URL.
        /// </summary>
        /// <param name="identity">CustomIdentity of an authenticated user</param>
        public static void RedirectFromLoginPage(CustomIdentity identity)
        {
            string cookieName = ConfigurationSettings.AppSettings[AUTHENTICATION_COOKIE_KEY];
            if(cookieName == null || cookieName.Trim() == String.Empty)
            {
                throw new Exception(" CustomAuthentication.Cookie.Name entry not found in appSettings section section of Web.config");
            }

            string cookieExpr = ConfigurationSettings.AppSettings[AUTHENTICATION_COOKIE_EXPIRATION_KEY];

            HttpRequest request = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            string encryptedUserDetails = Encrypt(identity);

            HttpCookie userCookie = new HttpCookie(cookieName.ToUpper(), encryptedUserDetails);
            if(cookieExpr != null && cookieExpr.Trim() != String.Empty)
            {
                userCookie.Expires = DateTime.Now.AddMinutes(int.Parse(cookieExpr));
            }
            response.Cookies.Add(userCookie);

            string returnUrl = request["ReturnUrl"];
            if(returnUrl != null && returnUrl.Trim() != String.Empty)
            {
                response.Redirect(returnUrl, false);
            }
            else
            {
                response.Redirect(request.ApplicationPath + "/default.aspx", false);
            }
        }
 private static void CheckToken(string token, out bool valid)
 {
     valid = false;
     try
     {
         var bpath = Convert.FromBase64String(token);
         token = System.Text.Encoding.Default.GetString(bpath);
         var jsonStr = "{'" + token.Replace("&", "','").Replace("=", "':'") + "'}";
         var serializer = new JavaScriptSerializer();
         var objs = serializer.Deserialize<TokenModel>(jsonStr);
         using (var accountService = DependencyResolver.Current.GetService<IAccountService>())
         {
             var user = accountService.GetAccounts().FirstOrDefault(n => n.Id == objs.appid && n.IsDeleted == false);
             if (user == null) return;
             var signature = SHA1_Hash(string.Format("appsecret={0}&random={1}", user.Token, objs.random));
             if (objs.signature.ToUpper() != signature) return;
             valid = true;
             var identity = new CustomIdentity(user);
             var principal = new CustomPrincipal(identity);
             HttpContext.Current.User = principal;
         }
     }
     catch (Exception)
     {
         valid = false;
     }
 }
示例#23
0
        /// <summary>
        /// Produces a string containing an encrypted string for an authenticated User Identity
        /// suitable for use in an HTTP cookie given a CustomIdentity
        /// </summary>
        /// <param name="identity">CustomIdentity class for the authenticated user</param>
        /// <returns>Encrypted string</returns>
        public static string Encrypt(CustomIdentity identity)
        {
            string encryptedString = String.Empty;
            try
            {
                StringBuilder en_str = new StringBuilder();
                Type t_Identity = identity.GetType();
                PropertyInfo[] propertyInfo = t_Identity.GetProperties();
                foreach(PropertyInfo property in propertyInfo)
                {
                    en_str.Append(property.GetValue(identity, null));
                    en_str.Append("|$|");
                }

                encryptedString = CustomEncryption.Encrypt(en_str.ToString());
            }
            catch(Exception e)
            {
                string str = e.Message;
                throw ;
            }
            return encryptedString;
        }
示例#24
0
        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }
            identity = (CustomIdentity)httpContext.User.Identity;
            var path = httpContext.Request.Path;

            if (path.StartsWithSegments(new PathString("/Home")) ||
                path.StartsWithSegments(new PathString("/ContentFiles")))
            {
                await _next(httpContext);

                return;
            }

            //identity = (CustomIdentity)httpContext.User.Identity;
            var requestBody = string.Empty;

            var sw = Stopwatch.StartNew();

            try
            {
                //if (httpContext.Request.Path.StartsWithSegments(new PathString("/api")))
                //{
                httpContext.Request.EnableBuffering();
                using var reader = new StreamReader(httpContext.Request.Body, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true);
                requestBody      = await reader.ReadToEndAsync();

                httpContext.Request.Body.Position = 0;
                //}

                await _next(httpContext);

                sw.Stop();
                var statusCode = httpContext.Response?.StatusCode;
                var level      = statusCode > 499 ? LogEventLevel.Error : LogEventLevel.Information;
                var log        = level == LogEventLevel.Error ? LogForErrorContext(httpContext, requestBody) : Log;
                if (path.StartsWithSegments(new PathString("/api/auth/SignIn")))
                {
                    var model = JsonConvert.DeserializeObject <LoginModel>(requestBody);
                    model.Password = null;
                    log            = log.ForContext("RequestForm", JsonConvert.SerializeObject(model));
                }
                else if (!string.IsNullOrEmpty(requestBody) || requestBody != "{}")
                {
                    log = log.ForContext("RequestForm", requestBody);
                }
                if (identity != null)
                {
                    log = log.ForContext("UserId", identity.UserId).ForContext("UserName", identity.Username);
                }

                log.Write(level, MessageTemplate, httpContext.Request.Method, httpContext.Request.Path, statusCode, sw.Elapsed.TotalMilliseconds);
            }
            // Never caught, because `LogException()` returns false.
            catch (Exception ex) when(LogException(httpContext, sw, ex, requestBody))
            {
            }
        }