public bool ValidateJwtAuthentication(ServiceRoute route, Dictionary <string, object> model, ref ServiceResult <object> result)
        {
            bool isSuccess = true;
            var  author    = HttpContext.Request.Headers["Authorization"];

            if (author.Count > 0)
            {
                isSuccess = _authorizationServerProvider.ValidateClientAuthentication(author).Result;
                if (!isSuccess)
                {
                    result = new ServiceResult <object> {
                        IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                    };
                }
                else
                {
                    var keyValue = model.FirstOrDefault();
                    if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType()))
                    {
                        dynamic instance = keyValue.Value;
                        instance.Payload = _authorizationServerProvider.GetPayloadString(author);
                        model.Remove(keyValue.Key);
                        model.Add(keyValue.Key, instance);
                    }
                }
            }
            else
            {
                result = new ServiceResult <object> {
                    IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error"
                };
                isSuccess = false;
            }
            return(isSuccess);
        }
 public void OnAuthorization(AuthorizationFilterContext filterContext)
 {
     if (filterContext.Route.ServiceDescriptor.EnableAuthorization())
     {
         if (filterContext.Route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString())
         {
             var author = filterContext.Context.Request.Headers["Authorization"];
             if (author.Count > 0)
             {
                 var isSuccess = _authorizationServerProvider.ValidateClientAuthentication(author).Result;
                 if (!isSuccess)
                 {
                     filterContext.Result = new HttpResultMessage <object> {
                         IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                     };
                 }
                 else
                 {
                     var payload = _authorizationServerProvider.GetPayloadString(author);
                     RpcContext.GetContext().SetAttachment("payload", payload);
                 }
             }
         }
     }
 }
Exemple #3
0
        private async Task OnTokenRequest(IHttpContext context)
        {
            context.SetHandled();

            var validationContext = context.GetValidationContext();
            await _authorizationServerProvider.ValidateClientAuthentication(validationContext)
            .ConfigureAwait(false);

            if (!validationContext.IsValidated)
            {
                context.Rejected(validationContext.ErrorPayload);
                return;
            }

            var expiryDate = DateTime.SpecifyKind(
                DateTime.FromBinary(_authorizationServerProvider.GetExpirationDate()),
                DateTimeKind.Utc);

            var token = new BearerToken
            {
                Token          = validationContext.GetToken(SecretKey, expiryDate),
                TokenType      = "bearer",
                ExpirationDate = _authorizationServerProvider.GetExpirationDate(),
                Username       = validationContext.IdentityName,
            };

            var dictToken = Json.Deserialize <Dictionary <string, object> >(Json.Serialize(token));

            OnSuccessTransformation?.Invoke(dictToken);

            await context
            .SendDataAsync(dictToken)
            .ConfigureAwait(false);
        }
        public async Task OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (filterContext.Route != null && filterContext.Route.ServiceDescriptor.EnableAuthorization())
            {
                if (filterContext.Route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString())
                {
                    var author = filterContext.Context.Request.Headers["Authorization"];
                    if (author.Count > 0)
                    {
                        var isSuccess = await _authorizationServerProvider.ValidateClientAuthentication(author);

                        if (!isSuccess)
                        {
                            filterContext.Result = new HttpResultMessage <object> {
                                IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                            };
                        }
                        else
                        {
                            var payload = _authorizationServerProvider.GetPayloadString(author);
                            RpcContext.GetContext().SetAttachment("payload", payload);
                        }
                    }
                }
            }
            var gatewayAppConfig = AppConfig.Options.ApiGetWay;

            if (String.Compare(filterContext.Path.ToLower(), gatewayAppConfig.TokenEndpointPath, true) == 0)
            {
                filterContext.Context.Items.Add("path", gatewayAppConfig.AuthorizationRoutePath);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BearerTokenModule"/> class.
        /// </summary>
        /// <param name="authorizationServerProvider">The authorization server provider.</param>
        /// <param name="routes">The routes.</param>
        /// <param name="secretKey">The secret key.</param>
        /// <param name="endpoint">The endpoint.</param>
        public BearerTokenModule(
            IAuthorizationServerProvider authorizationServerProvider,
            IEnumerable <string> routes    = null,
            SymmetricSecurityKey secretKey = null,
            string endpoint = "/token")
        {
            // TODO: Make secretKey parameter mandatory and and an overload that takes in a string for a secretKey
            SecretKey = secretKey ?? new SymmetricSecurityKey(Encoding.UTF8.GetBytes("0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF"));

            AddHandler(endpoint, HttpVerbs.Post, async(context, ct) =>
            {
                var validationContext = context.GetValidationContext();
                await authorizationServerProvider.ValidateClientAuthentication(validationContext);

                if (validationContext.IsValidated)
                {
                    var expiryDate = DateTime.SpecifyKind(DateTime.FromBinary(authorizationServerProvider.GetExpirationDate()), DateTimeKind.Utc);

                    await context.JsonResponseAsync(new BearerToken
                    {
                        Token          = validationContext.GetToken(SecretKey, expiryDate),
                        TokenType      = "bearer",
                        ExpirationDate = authorizationServerProvider.GetExpirationDate(),
                        Username       = validationContext.IdentityName,
                    });
                }
                else
                {
                    context.Rejected();
                }

                return(true);
            });

            AddHandler(ModuleMap.AnyPath, HttpVerbs.Any, (context, ct) =>
            {
                if (routes != null)
                {
                    var match = Match(routes, context);

                    if (!match)
                    {
                        return(Task.FromResult(false));
                    }
                }

                // decode token to see if it's valid
                if (context.GetSecurityToken(SecretKey) != null)
                {
                    return(Task.FromResult(false));
                }

                context.Rejected();

                return(Task.FromResult(true));
            });
        }
        public async Task <(bool, ServiceResult <object>)> ValidateJwtAuthentication(ServiceRoute route, Dictionary <string, object> model)
        {
            var result = ServiceResult <object> .Create(false, null);

            bool isSuccess = true;
            var  author    = HttpContext.Request.Headers["Authorization"];

            if (author.Count > 0)
            {
                isSuccess = await _authorizationServerProvider.ValidateClientAuthentication(author);

                if (!isSuccess)
                {
                    result = new ServiceResult <object> {
                        IsSucceed = false, StatusCode = Surging.Core.CPlatform.Exceptions.StatusCode.UnAuthentication, Message = "Invalid authentication credentials"
                    };
                }
                else
                {
                    var payload = _authorizationServerProvider.GetPayloadString(author);
                    RpcContext.GetContext().SetAttachment("payload", payload);
                    if (model.Count > 0)
                    {
                        var keyValue = model.FirstOrDefault();
                        if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType()))
                        {
                            dynamic instance = keyValue.Value;
                            instance.Payload = payload;
                            model.Remove(keyValue.Key);
                            model.Add(keyValue.Key, instance);
                        }
                    }
                }
            }
            else
            {
                result = new ServiceResult <object> {
                    IsSucceed = false, StatusCode = Surging.Core.CPlatform.Exceptions.StatusCode.RequestError, Message = "Request error"
                };
                isSuccess = false;
            }
            return(isSuccess, result);
        }
        /// <summary>
        /// 从容器中实例化对象,并调用对应方法
        /// </summary>
        /// <param name="method"></param>
        /// <param name="implementationMethod"></param>
        /// <returns>通过容器实例化ServiceEntity实体进行实例化,并调用相应的方法</returns>
        private ServiceEntity Create(MethodInfo method, MethodBase implementationMethod)
        {
            var serviceId         = _serviceIdGenerator.GenerateServiceId(method);
            var serviceDescriptor = new ServiceDescriptor {
                Id = serviceId
            };

            return(new ServiceEntity
            {
                Descriptor = serviceDescriptor,
                Func = async parameters =>
                {
                    // 从Microsoft.Extensions.DependencyInjection获取当前范围
                    var serviceScopeFactory = _serviceProvider.GetRequiredService <IServiceScopeFactory>();

                    if (parameters.Any(p => p.Key.Equals("token")))
                    {
                        if (!_authorization.ValidateClientAuthentication(parameters.First(l => l.Key.Equals("token")).Value.ToString()))
                        {
                            return Task.FromResult("{\"error\":\"failure token\"}");
                        }
                    }

                    using (var scope = serviceScopeFactory.CreateScope())
                    {
                        var par = implementationMethod.GetParameters()
                                  .Select(parameterInfo => _typeConvertibleService.Convert(parameters[parameterInfo.Name], parameterInfo.ParameterType))
                                  .ToArray();
                        var invoke = implementationMethod.Invoke(scope.ServiceProvider.GetRequiredService(method.DeclaringType), par);
                        var fullName = invoke.GetType().FullName;
                        if (fullName != null && fullName.Contains(typeof(Task).FullName ?? throw new InvalidOperationException()))
                        {
                            return Task.FromResult(((dynamic)invoke).Result);
                        }

                        return Task.FromResult(invoke);
                    }
                }
            });
Exemple #8
0
        public bool ValidateJwtAuthentication(ServiceRoute route, Dictionary <string, object> model, ref ServiceResult <object> result)
        {
            bool isSuccess = true;
            var  author    = HttpContext.Request.Headers["Authorization"].ToString();

            if (author.StartsWith("Bearer "))
            {
                author = author.Substring(7);
            }
            if (!string.IsNullOrEmpty(author))
            {
                isSuccess = _authorizationServerProvider.ValidateClientAuthentication(author).Result;
                if (!isSuccess)
                {
                    result = new ServiceResult <object> {
                        IsSucceed = false, StatusCode = (int)MessageStatusCode.UnAuthentication, Message = "不合法的身份凭证"
                    };
                }
                else
                {
                    var keyValue = model.FirstOrDefault();
                    if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType()))
                    {
                        var payload = _authorizationServerProvider.GetPayLoad(author);
                        RpcContext.GetContext().SetAttachment("payload", payload);
                    }
                }
            }
            else
            {
                result = new ServiceResult <object> {
                    IsSucceed = false, StatusCode = (int)MessageStatusCode.UnAuthentication, Message = "请先登录系统"
                };
                isSuccess = false;
            }
            return(isSuccess);
        }
        public async Task <AuthorServiceResult> ValidateJwtAuthentication(ServiceRoute route, string path, Dictionary <string, object> model)
        {
            AuthorServiceResult authorServiceResult = new AuthorServiceResult();
            // bool isSuccess = true;
            var author = HttpContext.Request.Headers["Authorization"];

            if (author.Count > 0)
            {
                var token = AuthenticationCommon.GetAuthToken(author);
                authorServiceResult.isSuccess = await _authorizationServerProvider.ValidateClientAuthentication(token);

                if (!authorServiceResult.isSuccess)
                {
                    authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult <object> {
                        IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                    };
                }
                else
                {
                    var onAuthorModel = new Dictionary <string, object>();
                    var payload       = _authorizationServerProvider.GetPayloadString(token);;
                    var keyValue      = model.FirstOrDefault();
                    if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType()))
                    {
                        dynamic instance = keyValue.Value;
                        instance.Payload = payload;
                        RpcContext.GetContext().SetAttachment("payload", instance.Payload.ToString());
                        model.Remove(keyValue.Key);
                        model.Add(keyValue.Key, instance);
                    }
                    //onAuthorModel.Add("input", JsonConvert.SerializeObject(new
                    //{
                    //    Path = path,
                    //    Payload = payload
                    //}));
                    //var data = await _serviceProxyProvider.Invoke<bool>(onAuthorModel, "api/user/onauthentication", "User");

                    //if (!data)
                    //{
                    //    authorServiceResult.isSuccess = false;
                    //    authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult<object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "没有该操作权限" };
                    //}
                    //else
                    //{
                    //    var keyValue = model.FirstOrDefault();
                    //    if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType()))
                    //    {
                    //        dynamic instance = keyValue.Value;
                    //        instance.Payload = payload;
                    //        RpcContext.GetContext().SetAttachment("payload", instance.Payload.ToString());
                    //        model.Remove(keyValue.Key);
                    //        model.Add(keyValue.Key, instance);
                    //    }
                    //}
                }
            }
            else
            {
                authorServiceResult.result = new Surging.Core.ApiGateWay.ServiceResult <object> {
                    IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error"
                };
                authorServiceResult.isSuccess = false;
            }
            return(authorServiceResult);
        }
Exemple #10
0
        public async Task OnAuthorization(AuthorizationFilterContext filterContext)
        {
            var gatewayAppConfig = AppConfig.Options.ApiGetWay;

            if (filterContext.Route != null && filterContext.Route.ServiceDescriptor.DisableNetwork())
            {
                var actionName = filterContext.Route.ServiceDescriptor.GroupName().IsNullOrEmpty()
                    ? filterContext.Route.ServiceDescriptor.RoutePath
                    : filterContext.Route.ServiceDescriptor.GroupName();
                filterContext.Result = new HttpResultMessage <object>
                {
                    IsSucceed = false, StatusCode = CPlatform.Exceptions.StatusCode.UnAuthorized,
                    Message   = $"{actionName}禁止被外网访问"
                };
            }
            else
            {
                var token = filterContext.Context.Request.Headers["Authorization"];

                if (filterContext.Route != null)
                {
                    if (filterContext.Route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString())
                    {
                        if (token.Any() && token.Count >= 1)
                        {
                            var validateResult = _authorizationServerProvider.ValidateClientAuthentication(token);
                            if (filterContext.Route.ServiceDescriptor.EnableAuthorization() &&
                                validateResult != ValidateResult.Success)
                            {
                                if (validateResult == ValidateResult.TokenFormatError)
                                {
                                    filterContext.Result = new HttpResultMessage <object>
                                    {
                                        IsSucceed  = false,
                                        StatusCode = CPlatform.Exceptions.StatusCode.UnAuthentication,
                                        Message    = "token格式不正确"
                                    };
                                    return;
                                }

                                if (validateResult == ValidateResult.SignatureError)
                                {
                                    filterContext.Result = new HttpResultMessage <object>
                                    {
                                        IsSucceed  = false,
                                        StatusCode = CPlatform.Exceptions.StatusCode.UnAuthentication,
                                        Message    = "token凭证不合法,请重新登录"
                                    };
                                    return;
                                }

                                if (validateResult == ValidateResult.TokenExpired)
                                {
                                    filterContext.Result = new HttpResultMessage <object>
                                    {
                                        IsSucceed = false, StatusCode = CPlatform.Exceptions.StatusCode.TokenExpired,
                                        Message   = "登录超时,请重新登录"
                                    };
                                    return;
                                }
                            }

                            var payload = _authorizationServerProvider.GetPayload(token);

                            var claimsIdentity = new ClaimsIdentity();

                            foreach (var item in payload)
                            {
                                claimsIdentity.AddClaim(new Claim(item.Key, item.Value.ToString()));
                            }

                            if (!gatewayAppConfig.AuthorizationRoutePath.IsNullOrEmpty() &&
                                filterContext.Route.ServiceDescriptor.EnableAuthorization())
                            {
                                var rpcParams = new Dictionary <string, object>()
                                {
                                    { "serviceId", filterContext.Route.ServiceDescriptor.Id }
                                };
                                var authorizationRoutePath =
                                    await _serviceRouteProvider.GetRouteByPathOrRegexPath(
                                        gatewayAppConfig.AuthorizationRoutePath, HttpMethod.POST.ToString());

                                if (authorizationRoutePath == null)
                                {
                                    filterContext.Result = new HttpResultMessage <object>
                                    {
                                        IsSucceed = false, StatusCode = CPlatform.Exceptions.StatusCode.RequestError,
                                        Message   = "没有找到实现接口鉴权的WebApi的路由信息"
                                    };
                                    return;
                                }

                                foreach (var kv in payload)
                                {
                                    RpcContext.GetContext().SetAttachment(kv.Key, kv.Value);
                                }

                                var checkPermissionResult =
                                    await _serviceProxyProvider.Invoke <IDictionary <string, object> >(rpcParams,
                                                                                                       gatewayAppConfig.AuthorizationRoutePath, HttpMethod.POST,
                                                                                                       gatewayAppConfig.AuthorizationServiceKey);

                                if (checkPermissionResult == null || !checkPermissionResult.ContainsKey("isPermission"))
                                {
                                    filterContext.Result = new HttpResultMessage <object>
                                    {
                                        IsSucceed = false, StatusCode = StatusCode.UnAuthorized,
                                        Message   = $"接口鉴权返回数据格式错误,鉴权接口返回数据格式必须为字典,且必须包含IsPermission的key"
                                    };
                                    return;
                                }

                                var isPermission = Convert.ToBoolean(checkPermissionResult["isPermission"]);
                                if (!isPermission)
                                {
                                    var actionName = filterContext.Route.ServiceDescriptor.GroupName().IsNullOrEmpty()
                                        ? filterContext.Route.ServiceDescriptor.RoutePath
                                        : filterContext.Route.ServiceDescriptor.GroupName();
                                    filterContext.Result = new HttpResultMessage <object>
                                    {
                                        IsSucceed = false, StatusCode = StatusCode.UnAuthorized,
                                        Message   = $"没有请求{actionName}的权限"
                                    };
                                    return;
                                }

                                foreach (var kv in checkPermissionResult)
                                {
                                    if (kv.Key == "isPermission")
                                    {
                                        continue;
                                    }

                                    if (kv.Value == null)
                                    {
                                        continue;
                                    }

                                    claimsIdentity.AddClaim(new Claim(kv.Key, kv.Value.ToString()));
                                }
                            }

                            filterContext.Context.User = new ClaimsPrincipal(claimsIdentity);
                        }
                        else
                        {
                            if (filterContext.Route.ServiceDescriptor.EnableAuthorization())
                            {
                                filterContext.Result = new HttpResultMessage <object>
                                {
                                    IsSucceed = false, StatusCode = CPlatform.Exceptions.StatusCode.UnAuthentication,
                                    Message   = $"请先登录系统"
                                };
                                return;
                            }
                            else
                            {
                                filterContext.Context.User = null;
                            }
                        }
                    }
                    else
                    {
                        if (filterContext.Route.ServiceDescriptor.EnableAuthorization())
                        {
                            filterContext.Result = new HttpResultMessage <object>
                            {
                                IsSucceed = false, StatusCode = CPlatform.Exceptions.StatusCode.UnAuthentication,
                                Message   = $"暂不支持{filterContext.Route.ServiceDescriptor.AuthType()}类型的身份认证方式"
                            };
                        }
                    }
                }
            }

            if (string.Compare(filterContext.Path.ToLower(), gatewayAppConfig.TokenEndpointPath, true) == 0)
            {
                filterContext.Context.Items.Add("path", gatewayAppConfig.AuthenticationRoutePath);
            }
        }
        /// <summary>
        /// Module's Constructor
        /// </summary>
        /// <param name="authorizationServerProvider">The AuthorizationServerProvider to use</param>
        /// <param name="routes">The routes to authorizate</param>
        /// <param name="secretKey">The secret key to encrypt tokens</param>
        public BearerTokenModule(IAuthorizationServerProvider authorizationServerProvider,
                                 IEnumerable <string> routes = null, string secretKey = "0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF")
        {
            AddHandler("/token", HttpVerbs.Post, (server, context) =>
            {
                var validationContext = context.GetValidationContext();
                authorizationServerProvider.ValidateClientAuthentication(validationContext);

                if (validationContext.IsValidated)
                {
                    context.JsonResponse(new BearerToken
                    {
                        Token          = validationContext.GetToken(secretKey),
                        TokenType      = "bearer",
                        ExpirationDate = authorizationServerProvider.GetExpirationDate(),
                        Username       = validationContext.ClientId
                    });
                }
                else
                {
                    context.Rejected();
                }

                return(true);
            });

            AddHandler(ModuleMap.AnyPath, HttpVerbs.Any, (server, context) =>
            {
                if (routes != null && routes.Contains(context.RequestPath()) == false)
                {
                    return(false);
                }

                var authHeader = context.RequestHeader(AuthorizationHeader);

                if (string.IsNullOrWhiteSpace(authHeader) == false && authHeader.StartsWith("Bearer "))
                {
                    try
                    {
                        var token   = authHeader.Replace("Bearer ", "");
                        var payload = JWT.JsonWebToken.DecodeToObject(token, secretKey) as IDictionary <string, object>;

                        if (payload == null || payload.Count == 0)
                        {
                            throw new Exception("Invalid token");
                        }

                        return(false);
                    }
                    catch (JWT.SignatureVerificationException)
                    {
                        server.Log.DebugFormat("Invalid token {0}", authHeader);
                        throw;
                    }
                    catch (Exception ex)
                    {
                        server.Log.Error(ex);
                    }
                }

                context.Rejected();

                return(true);
            });
        }