public void Execute(IHttpRequest httpReq, IHttpResponse httpRes)
        {
            EndpointHost.Config.AssertFeatures(Feature.Metadata);

            httpRes.ContentType = "text/xml";

            var baseUri = httpReq.GetParentBaseUrl();
            var optimizeForFlash = httpReq.QueryString["flash"] != null;
            var includeAllTypesInAssembly = httpReq.QueryString["includeAllTypes"] != null;
            var operations = new XsdMetadata(
                EndpointHost.Metadata, flash: optimizeForFlash, includeAllTypes: includeAllTypesInAssembly);

            try
            {
                var wsdlTemplate = GetWsdlTemplate(operations, baseUri, optimizeForFlash, includeAllTypesInAssembly, httpReq.GetBaseUrl());
                httpRes.Write(wsdlTemplate.ToString());
            }
            catch (Exception ex)
            {
                log.Error("Autogeneration of WSDL failed.", ex);

                httpRes.Write("Autogenerated WSDLs are not supported "
                    + (Env.IsMono ? "on Mono" : "with this configuration"));
            }
        }
 public static string GetAbsoluteUrl(this IHttpRequest httpReq, string url)
 {
     if (url.SafeSubstring(0, 2) == "~/")
     {
         url = httpReq.GetBaseUrl().CombineWith(url.Substring(2));
     }
     return(url);
 }
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (AuthService.AuthProviders == null)
            {
                throw new InvalidOperationException("The AuthService must be initialized by calling "
                                                    + "AuthService.Init to use an authenticate attribute");
            }

            var matchingOAuthConfigs = AuthService.AuthProviders.Where(x =>
                                                                       this.Provider.IsNullOrEmpty() ||
                                                                       x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
                               .Fmt(this.Provider ?? "any"));
                res.EndServiceStackRequest();
                return;
            }

            if (matchingOAuthConfigs.Any(x => x.Provider == DigestAuthProvider.Name))
            {
                AuthenticateIfDigestAuth(req, res);
            }

            if (matchingOAuthConfigs.Any(x => x.Provider == BasicAuthProvider.Name))
            {
                AuthenticateIfBasicAuth(req, res);
            }

            using (var cache = req.GetCacheClient())
            {
                var session = req.GetSession();

                if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
                {
                    var htmlRedirect = HtmlRedirect ?? AuthService.HtmlRedirect;
                    if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(ContentType.Html))
                    {
                        var url = htmlRedirect;
                        if (url.SafeSubstring(0, 2) == "~/")
                        {
                            url = req.GetBaseUrl().CombineWith(url.Substring(2));
                        }
                        url = url.AddQueryParam("redirect", req.AbsoluteUri);
                        res.RedirectToUrl(url);
                        return;
                    }

                    AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
                }
            }
        }
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (AuthService.AuthProviders == null) throw new InvalidOperationException("The AuthService must be initialized by calling "
                 + "AuthService.Init to use an authenticate attribute");

            var matchingOAuthConfigs = AuthService.AuthProviders.Where(x =>
                this.Provider.IsNullOrEmpty()
                || x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
                    .Fmt(this.Provider ?? "any"));
                res.EndServiceStackRequest();
                return;
            }

            AuthenticateIfDigestAuth(req, res);
            AuthenticateIfBasicAuth(req, res);

            using (var cache = req.GetCacheClient())
            {
                var sessionId = req.GetSessionId();
                var session = sessionId != null ? cache.GetSession(sessionId) : null;

                if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
                {
                    var htmlRedirect = HtmlRedirect ?? AuthService.HtmlRedirect;
                    if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(ContentType.Html))
                    {
                        var url = htmlRedirect;
                        if (url.SafeSubstring(0, 2) == "~/")
                        {
                            url = req.GetBaseUrl().CombineWith(url.Substring(2));
                        }
                        url = url.AddQueryParam("redirect", req.AbsoluteUri);
                        res.RedirectToUrl(url);
                        return;
                    }

                    AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
                }
            }
        }
Example #5
0
        public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
        {
            try
            {
                response.ContentType = "application/json";
                var basePath = request.GetBaseUrl();
                var result   = new SwaggerResourcesResponse
                {
                    BasePath   = basePath,
                    Apis       = new List <SwaggerResourceRef>(),
                    ApiVersion = _config.ApiVersion,
                    Info       = new SwaggerInfo
                    {
                        Title = _config.Title ?? "Ant-SOA-API",
                    }
                };

                if (_config.UseBasicAuth)
                {
                    var basicAuth = request.GetBasicAuthUserAndPassword();
                    if (basicAuth == null)
                    {
                        result.Info.Title = "Auth Error";
                        response.Write(result.ToJson());
                        response.EndRequest(true);
                        return;
                    }
                    else
                    {
                        var userName  = basicAuth.Value.Key;
                        var password  = basicAuth.Value.Value;
                        var localAuth = _config.GetLocalAuthModel();
                        if (!localAuth.UserName.Equals(userName) && !localAuth.Password.Equals(password))
                        {
                            result.Info.Title = "Auth Error";
                            response.Write(result.ToJson());
                            response.EndRequest(true);
                            return;
                        }
                    }
                }
                result.Apis.Add(new SwaggerResourceRef
                {
                    Path        = request.ResolveAbsoluteUrl("~/" + SwaggerApiService.RESOURCE_PATH),
                    Description = _config.HostConfig.MetadataMap.FirstOrDefault().Value.ServiceName
                });

                result.Apis = result.Apis.OrderBy(a => a.Path).ToList();
                if (ResourcesResponseFilter != null)
                {
                    ResourcesResponseFilter(result);
                }

                response.Write(result.ToJson());
                response.EndRequest(true);
            }
            catch (Exception)
            {
                response.EndRequestWithNoContent();
            }
        }
        public void Execute(IHttpRequest httpReq, IHttpResponse httpRes)
        {
            EndpointHost.Config.AssertFeatures(Feature.Metadata);

            httpRes.ContentType = "text/xml";

            var baseUri          = httpReq.GetParentBaseUrl();
            var optimizeForFlash = httpReq.QueryString["flash"] != null;
            var operations       = new XsdMetadata(EndpointHost.Metadata, flash: optimizeForFlash);

            try
            {
                var wsdlTemplate = GetWsdlTemplate(operations, baseUri, optimizeForFlash, httpReq.GetBaseUrl());
                httpRes.Write(wsdlTemplate.ToString());
            }
            catch (Exception ex)
            {
                log.Error("Autogeneration of WSDL failed.", ex);

                httpRes.Write("Autogenerated WSDLs are not supported "
                              + (Env.IsMono ? "on Mono" : "with this configuration"));
            }
        }
Example #7
0
        public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
        {
            response.ContentType = "application/json";
            var path              = request.PathInfo.Substring(request.PathInfo.IndexOf(RESOURCE_PATH, StringComparison.Ordinal) + RESOURCE_PATH.Length);
            var basePath          = request.GetBaseUrl();
            var serviceController = _config.HostConfig.ServiceController as ServiceController;

            if (serviceController == null)
            {
                return;
            }

            var models = new Dictionary <string, SwaggerModel>();

            foreach (KeyValuePair <string, ServiceMetadata> item in _config.HostConfig.MetadataMap)
            {
                var name = item.Key;

                if (!serviceController.RestPathMap.ContainsKey(name))
                {
                    return;
                }
                var map = serviceController.RestPathMap[name];

                List <RestPath> paths = new List <RestPath>();
                //每个方法
                foreach (KeyValuePair <string, List <RestPath> > mapItem in map)
                {
                    paths.AddRange(mapItem.Value);
                }

                foreach (var restPath in paths)
                {
                    string verb = (typeof(ISpecificRecord).IsAssignableFrom(restPath.RequestType)) ? "POST" : "GET";
                    ParseModel(models, restPath.RequestType, restPath.Path, verb);
                }

                var apis = paths.Select(p => FormatMethodDescription(p, models)).ToArray().OrderBy(md => md.Path).ToList();

                var result = new SwaggerApiDeclaration
                {
                    ApiVersion   = _config.ApiVersion,
                    ResourcePath = path,
                    BasePath     = basePath,
                    Apis         = apis,
                    Models       = models
                };

                if (OperationFilter != null)
                {
                    apis.ForEach(x => x.Operations.ForEach(OperationFilter));
                }

                if (ApiDeclarationFilter != null)
                {
                    ApiDeclarationFilter(result);
                }


                response.Write(result.ToJson());
                response.EndRequest(true);
            }
        }