Пример #1
0
        public async Task Invoke(HttpContext context)
        {
            var request = context.Request;

            if (!ExcludeApiUrlForAuthentication.ExcludeList.Contains(request.Path.Value))
            {
                if (request.Headers.Keys.Contains("ApiKey") && request.Headers.Keys.Contains("DeviceNumber"))
                {
                    var key           = request.Headers["ApiKey"];
                    var deviceNumber  = request.Headers["DeviceNumber"];
                    var originalValue = string.Empty;
                    try
                    {
                        originalValue = _webHelper.Decrypt(key);
                    }
                    catch
                    {
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    }
                    string[] array = originalValue.Split(new string[] { "@_@" }, StringSplitOptions.RemoveEmptyEntries);

                    if (array.Count() == 3 && int.TryParse(array[0], out int userId))
                    {
                        try
                        {
                            var user = _userService.GetUserById(userId);
                            if (user.IsActive && !user.IsDeleted)
                            {
                                if (user.DeviceNumber.Equals(array[1]) && user.DeviceNumber.Equals(deviceNumber))
                                {
                                    await _next(context);
                                }
                                else
                                {
                                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                                }
                            }
                            else
                            {
                                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        }
                    }
                }
                else
                {
                    var response = context.Response;
                    response.StatusCode = StatusCodes.Status400BadRequest;
                }
            }
            else
            {
                await _next(context);
            }
        }