Beispiel #1
0
        public async Task <IActionResult> GetRefreshAsync([FromHeader] String source,
                                                          [FromHeader] String authorization)
        {
            var response = new Response <JwtAuthorData>();

            try {
                var member = new MemberInfos();

                var result = await _IJwtRedis.RefreshAsync(authorization, member);

                if (result != null)
                {
                    response.Code = true;
                    response.Data = result;
                }
                else
                {
                    return(BadRequest("请求刷新失败!"));
                }
            }
            catch (Exception ex) {
                response.SetError(ex, this._ILogger);
            }
            return(response.ToHttpResponse());
        }
Beispiel #2
0
        /// <summary>
        /// 新增 Token
        /// </summary>
        /// <param name="dto">用户信息数据传输对象</param>
        /// <returns></returns>
        public JwtAuthorData Create(MemberInfos dto)
        {
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            SymmetricSecurityKey    key          = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:JwtBearer:SecurityKey"]));

            DateTime authTime  = DateTime.UtcNow;
            DateTime expiresAt = authTime.AddMinutes(Convert.ToDouble(_configuration["Authentication:JwtBearer:TokenMinutes"]));

            //将用户信息添加到 Claim 中
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);

            IEnumerable <Claim> claims = new Claim[] {
                new Claim(ClaimTypes.NameIdentifier, dto.MemberId.ToString()),
                new Claim(ClaimTypes.Name, string.IsNullOrEmpty(dto.Name)?"":dto.Name),
                new Claim(ClaimTypes.MobilePhone, string.IsNullOrEmpty(dto.Phone)?"":dto.Phone),
                new Claim(ClaimTypes.SerialNumber, string.IsNullOrEmpty(dto.Code)?"":dto.Code),
                new Claim(ClaimTypes.Upn, string.IsNullOrEmpty(dto.Alipay)?"":dto.Alipay),
                new Claim(ClaimTypes.Spn, string.IsNullOrEmpty(dto.OpenId)?"":dto.OpenId),
                new Claim(ClaimTypes.Expiration, expiresAt.ToString())
            };

            identity.AddClaims(claims);
            // 签发一个加密后的用户信息凭证,用来标识用户的身份,并把用户信息添加请求上下文中
            _httpContextAccessor.HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

            var tokenDescriptor = new SecurityTokenDescriptor {
                Subject            = new ClaimsIdentity(claims),                                //创建声明信息
                Issuer             = _configuration["Authentication:JwtBearer:Issuer"],         //Jwt token 的签发者
                Audience           = _configuration["Authentication:JwtBearer:Audience"],       //Jwt token 的接收者
                Expires            = expiresAt,                                                 //过期时间
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256) //创建 token
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            //tokenHandler.CreateSecurityTokenReference(token, false);

            //存储 Token 信息
            var jwt = new JwtAuthorData {
                MemberId = dto.MemberId,
                Token    = tokenHandler.WriteToken(token),
                Auths    = new DateTimeOffset(authTime).ToUnixTimeMilliseconds(),
                Expires  = new DateTimeOffset(expiresAt).ToUnixTimeMilliseconds(),
            };

            if (!_tokens.Add(jwt))
            {
                jwt = default(JwtAuthorData);
            }
            return(jwt);
        }
Beispiel #3
0
        //=> await IsActiveAsync(GetCurrentAsync());

        /// <summary>
        /// 刷新 Token
        /// </summary>
        /// <param name="token">Token</param>
        /// <param name="dto">用户信息</param>
        /// <returns></returns>
        public async Task <JwtAuthorData> RefreshAsync(string token, MemberInfos dto)
        {
            var jwtOld = GetExistenceToken(token);

            if (jwtOld == null)
            {
                return(null);
            }
            var jwt = Create(dto);

            //停用修改前的 Token 信息
            await DeactivateCurrentAsync();

            return(jwt);
        }
Beispiel #4
0
        public async Task <IActionResult> PostUserRegisterAsync([FromHeader] String source,
                                                                [FromHeader] String authorization,
                                                                [FromBody] RegisterPost item)
        {
            var response = new Response <JwtAuthorData>();
            var message  = string.Empty;

            try {
                var entity = await _IMemberInfosRepository.FirstOrDefaultAsync(a => a.Uid == item.uid && a.OpenId == item.openid && a.IsEnable == 1);

                if (entity == null)
                {
                    entity             = new MemberInfos();
                    entity.Code        = SnowFlake.GetInstance().GetUniqueShortId(8);
                    entity.NickName    = item.name;
                    entity.Name        = item.name;
                    entity.Sex         = item.gender == "男" ? 1 : 0;
                    entity.Avatar      = item.iconurl;
                    entity.Uid         = item.uid;
                    entity.OpenId      = item.openid;
                    entity.Phone       = item.phone;
                    entity.Password    = Tools.Md5("000000");
                    entity.Beans       = 0;
                    entity.BeansTotals = 0;

                    entity.NewsNumber      = 0;
                    entity.FollowNumber    = 0;
                    entity.FavoritesNumber = 0;
                    entity.FansNumber      = 0;

                    entity.IsNoviceTask  = 0;
                    entity.IsEnable      = 1;
                    entity.LastLoginTime = System.DateTime.Now;
                    entity.CreateTime    = System.DateTime.Now;
                    entity.Remarks       = "微信首次登录注册。";

                    await _IMemberInfosRepository.AddAsync(entity);

                    await _IMemberInfosRepository.SaveChangesAsync();

                    message = "初始登录密码为【000000】";

                    var taskNoviceLogs = await _ITaskInfoRepository.Query(a => a.IsNoviceTask == 1 && a.IsEnable == 1)
                                         .Select(a => new TaskNoviceLog()
                    {
                        TaskId        = a.TaskId,
                        CategoryFixed = a.CategoryFixed,
                        CategoryDay   = a.CategoryDay,
                        MemberId      = entity.MemberId,
                        IsEnable      = 1
                    })
                                         .ToListAsync();

                    await _ITaskNoviceLogRepository.BatchAddAsync(taskNoviceLogs);
                }
                else
                {
                    message = "已注册,初始登录密码为【000000】";
                }
                var result = _IJwtRedis.Create(entity);
                if (result != null)
                {
                    //await _IJwtRedis.DeactivateAsync(authorization);
                    response.Code    = true;
                    response.Message = message;
                    response.Data    = result;
                }
                else
                {
                    return(BadRequest("授权失败!"));
                }
            }
            catch (Exception ex) {
                response.SetError(ex, this._ILogger);
            }
            return(response.ToHttpResponse());
        }
Beispiel #5
0
        public virtual void Call(Socket socket, Object obj)
        {
            Timer++;

            wath.Start();
            DataEventArgs e = (DataEventArgs)obj;

            LastParam   = _serializer.ToString(e);
            LastRunTime = DateTime.Now;
            LastMethod  = e.ActionParam;
            string code = string.Empty;

            if (e.ActionCmd == CallActionCmd.Register.ToString())
            {
                e.Binary     = this._serializer.ToBinary(RegisterInfo);
                e.StatusCode = StatusCode.Success;
            }
            else if (e.ActionCmd == CallActionCmd.Ping.ToString())
            {
                e.ActionCmd  = CallActionCmd.Pong.ToString();
                e.Binary     = this._serializer.ToBinary("Pong");
                e.StatusCode = StatusCode.Success;
            }
            else if (e.ActionCmd == CallActionCmd.Validate.ToString())
            {
                e.HttpSessionId = Guid.NewGuid().ToString("N");
            }
            else if (e.ActionCmd == CallActionCmd.Call.ToString())
            {
                int p = e.ActionParam.LastIndexOf(".");

                code = e.ActionParam.Substring(p + 1);
                if (string.IsNullOrEmpty(code))
                {
                    e.StatusCode = StatusCode.Serious;
                }
                else
                {
                    if (MemberInfos.ContainsKey(code))
                    {
                        try
                        {
                            string name = MemberInfos[code].Item1;
                            MemberInfos[code] = new Tuple <string, MethodInfo, int, long>(MemberInfos[code].Item1, MemberInfos[code].Item2, MemberInfos[code].Item3 + 1, MemberInfos[code].Item4 + e.Binary.Buffer.LongLength);
                            MethodInfo method     = MemberInfos[code].Item2;
                            string     param      = this._serializer.ToEntity <string>(e.Binary);
                            object     parameters = this._serializer.ToEntity <List <object> >(param);
                            if (parameters == null)
                            {
                                parameters = new List <object>();
                            }
                            parameters = new MethodParam().CorrectParameters(method, (List <object>)parameters);
                            Object   bll      = ApplicationContext.GetObject(name);
                            object[] arrparam = ((List <object>)parameters).ToArray();
                            var      result   = method.Invoke(bll, arrparam);
                            if (!method.ReturnType.Equals(typeof(void)))
                            {
                                e.Binary = this._serializer.ToBinary(result);
                                if (e.Param == null)
                                {
                                    e.Param = new System.Collections.ArrayList();
                                }
                                for (int i = 0; i < arrparam.Length; i++)
                                {
                                    e.Param.Add(arrparam[i]);
                                }
                            }
                            else
                            {
                                e.Binary = null;
                            }

                            e.StatusCode = StatusCode.Success;
                        }
                        catch (Exception ex)
                        {
                            _log.Error(ex);
                            e.LastError = ex.Message;
                            if (ex.InnerException != null)
                            {
                                e.LastError = e.LastError + ex.InnerException.Message;
                                _log.Error(ex.InnerException);
                            }

                            e.StatusCode = StatusCode.Serious;
                            LastError    = e.LastError;
                            IsStart      = false;
                        }
                    }
                    else
                    {
                        e.LastError = LastError = "服务不存在";
                        _log.Error("服务不存在");
                        e.StatusCode = StatusCode.NoExit;
                    }
                }
            }
            Send(socket, e);
            wath.Stop();
            _log.Info(e.ActionParam + ":" + e.CallHashCode + ":" + e.TaskId + ":" + wath.ElapsedMilliseconds);
            monitr.Write(e.TaskId, "", "." + code, wath.ElapsedMilliseconds, e.Binary.Buffer.LongLength.ToString());
        }
        private void DrawValue(Rect rect, MemberInfos infos, string name, string assemblyQualifiedName, ObjectType objectType, string typeName, SerializedProperty valueProperty, SerializedObject serializedObject)
        {
            var fieldProp = valueProperty.GetPropertyOfType(objectType);

            if (fieldProp == null)
            {
                return;
            }

            var typeProperty         = valueProperty.FindPropertyRelative(ValueFields.Type);
            var fullTypeNameProperty = valueProperty.FindPropertyRelative(ValueFields.FullTypeName);

            typeProperty.intValue            = (int)objectType;
            fullTypeNameProperty.stringValue = assemblyQualifiedName;
            serializedObject.ApplyModifiedProperties();

            switch (objectType)
            {
            case ObjectType.Bounds:
            case ObjectType.Rect:
            case ObjectType.Matrix4x4:
            case ObjectType.SerializableType:
            case ObjectType.Array:
            case ObjectType.List:
                if (GUI.Button(rect, WIZARD))
                {
                    var wizard = ScriptableWizard.DisplayWizard <PropertyWizard>(string.Empty, "Save");
                    wizard.infos              = infos;
                    wizard.type               = objectType;
                    wizard.typeOf             = Type.GetType(assemblyQualifiedName);
                    wizard.serializedProperty = fieldProp;
                    wizard.path               = fieldProp.propertyPath;
                    wizard.onClose            = OnPropertyWizardClose;
                }
                return;
            }

            var label = new GUIContent(typeName);

            switch (objectType)
            {
            case ObjectType.Boolean:
            case ObjectType.Int32:
            case ObjectType.Int64:
            case ObjectType.Single:
            case ObjectType.Double:
            case ObjectType.String:
                EditorGUI.PropertyField(rect, fieldProp, label, false);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.UInt64:
                var   oldValue    = fieldProp.stringValue;
                var   ulongString = EditorGUI.TextField(rect, label, fieldProp.stringValue);
                ulong ulongVal;

                if (!ulong.TryParse(ulongString, out ulongVal))
                {
                    ulongString = oldValue;
                }

                if (string.IsNullOrEmpty(ulongString))
                {
                    ulongString = "0";
                }

                fieldProp.stringValue = ulongString;
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.LayerMask:
            case ObjectType.Color:
            case ObjectType.AnimationCurve:
                EditorGUI.PropertyField(rect, fieldProp, GUIContent.none, false);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.Byte:
                fieldProp.intValue = EditorFields.ByteField(rect, label, (byte)fieldProp.intValue);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.SByte:
                fieldProp.intValue = EditorFields.SByteField(rect, label, (sbyte)fieldProp.intValue);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.Char:
                fieldProp.intValue = EditorFields.CharField(rect, label, (char)fieldProp.intValue);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.Int16:
                fieldProp.intValue = EditorFields.ShortField(rect, label, (short)fieldProp.intValue);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.UInt16:
                fieldProp.intValue = EditorFields.UShortField(rect, label, (ushort)fieldProp.intValue);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.UInt32:
                fieldProp.longValue = EditorFields.UIntField(rect, label, (uint)fieldProp.longValue);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.Enum:
            {
                var  typeOf         = Type.GetType(assemblyQualifiedName);
                var  flagsAttribute = typeOf.GetCustomAttributes(typeof(FlagsAttribute), false);
                Enum enumValue;

                if (flagsAttribute != null && flagsAttribute.Length >= 1)
                {
                    enumValue = EditorGUI.EnumMaskPopup(rect, GUIContent.none, (Enum)Enum.ToObject(typeOf, fieldProp.longValue));
                }
                else
                {
                    enumValue = EditorGUI.EnumPopup(rect, (Enum)Enum.ToObject(typeOf, fieldProp.longValue));
                }

                try
                {
                    fieldProp.longValue = (int)Enum.ToObject(typeOf, enumValue);
                    serializedObject.ApplyModifiedProperties();
                }
                catch
                {
                    fieldProp.longValue = (long)Enum.ToObject(typeOf, enumValue);
                    serializedObject.ApplyModifiedProperties();
                }
            }
            break;

            case ObjectType.Vector2:
                fieldProp.vector2Value = EditorGUI.Vector2Field(rect, GUIContent.none, fieldProp.vector2Value);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.Vector3:
                fieldProp.vector3Value = EditorGUI.Vector3Field(rect, GUIContent.none, fieldProp.vector3Value);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.Vector4:
                fieldProp.vector4Value = EditorGUI.Vector4Field(rect, GUIContent.none, fieldProp.vector4Value);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.Quaternion:
                fieldProp.quaternionValue = EditorFields.QuaternionField(rect, GUIContent.none, fieldProp.quaternionValue);
                serializedObject.ApplyModifiedProperties();
                break;

            case ObjectType.UnityObject:
            {
                var typeOf = Type.GetType(assemblyQualifiedName);
                fieldProp.objectReferenceValue = EditorGUI.ObjectField(rect, GUIContent.none, fieldProp.objectReferenceValue, typeOf, true);
                serializedObject.ApplyModifiedProperties();
            }
            break;
            }
        }