Example #1
0
        public override void InitializeServiceClient <T>(ServiceClient <T> client)
        {
            if (!BasicMode)
            {
                // For bear mode
                // Step 1: get challenge response from /v2/ API. THe response Www-Authenticate header is token server URL.
                string              challegeUrl    = (LoginUrl.StartsWith("https://") ? "" : "https://") + LoginUrl + (LoginUrl.EndsWith("/") ? "" : "/") + "v2/";
                HttpClient          runtimeClient  = new HttpClient();
                HttpResponseMessage response       = null;
                string              tokenServerUrl = "";
                try {
                    response       = runtimeClient.GetAsync(challegeUrl, RequestCancellationToken).GetAwaiter().GetResult();
                    tokenServerUrl = response.Headers.GetValues("Www-Authenticate").FirstOrDefault();
                } catch (Exception e) {
                    Console.WriteLine("v2 call throws exception {0}", e.Message);
                }

                if (!String.IsNullOrEmpty(tokenServerUrl))
                {
                    // Step 2: present username and password to token server to get access token
                    // TODO: Call token server to get access token
                    return;
                }
            }

            AuthHeader = EncodeTo64(Username + ":" + Password);
        }
Example #2
0
        public ActionResult LoginAJAX(UserInfoModel _UserInfoData)
        {
            LoginUrl _LoginUrl = new LoginUrl();

            if (_RanKDistributionModel.CheckLogin(_UserInfoData))
            {
                //  $(locatoin).attr('href', '~/RanKDistribution/Index');
                _LoginUrl.Url            = "/RanKDistribution";
                _LoginUrl.IsLoginSuccess = true;
                Session["userame"]       = _UserInfoData.UserName;
                Session["auth"]          = true;



                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                                                 //你想要存放在 User.Identy.Name 的值,通常是使用者帳號
                                                                                 _UserInfoData.UserName,
                                                                                 DateTime.Now,
                                                                                 DateTime.Now.AddMinutes(30),
                                                                                 true,       //將管理者登入的 Cookie 設定成 Session Cookie
                                                                                 "userdata", //userdata看你想存放啥
                                                                                 FormsAuthentication.FormsCookiePath);


                string encTicket = FormsAuthentication.Encrypt(ticket);

                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                cookie.HttpOnly = true;

                Response.Cookies.Add(cookie);



                // return Json(new { msg = "密碼正確 " });
            }
            else
            {
                _LoginUrl.Url            = "";
                _LoginUrl.IsLoginSuccess = false;
            }
            return(Json(_LoginUrl));
        }
Example #3
0
        public string GetAuthorizationLink()
        {
            //append the current querystring to the login url
            try
            {
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    var currentUrlParts = HttpContext.Current.Request.RawUrl.Split('?');
                    if (currentUrlParts.Length > 0) //we have a querstring
                    {
                        if (LoginUrl.Contains("?"))
                        {
                            return(string.Concat(LoginUrl, "&", currentUrlParts[1]));
                        }

                        return(string.Concat(LoginUrl, "?", currentUrlParts[1]));
                    }
                }
            }
            catch { }
            return(LoginUrl);
        }
 private bool Valid()
 {
     return(!LoginUrl.NullOrEmpty() &&
            !LogoutUrl.NullOrEmpty() &&
            !LoginReturnUrlParameter.NullOrEmpty());
 }
Example #5
0
 /// <summary>
 /// Creates an inline keyboard button that opens a HTTP URL to automatically authorize the user
 /// </summary>
 /// <param name="text">Label text on the button</param>
 /// <param name="loginUrl">An HTTP URL used to automatically authorize the user</param>
 /// <returns></returns>
 public static InlineKeyboardButton WithLoginUrl(string text, LoginUrl loginUrl) =>
 new InlineKeyboardButton
 {
     Text     = text,
     LoginUrl = loginUrl
 };
        private void Login()
        {
            foreach (var handler in _systemAuthenticationHandlers)
            {
                handler.OnLoginStart();
            }
            foreach (var handler in _customAuthenticationHandlers)
            {
                handler.OnLoginStart();
            }
            ////HACK:改成配置项 不要写死在程序中
            var httpContext = HttpContext.Current;
            var account     = httpContext.Request["account"];
            var password    = httpContext.Request["password"];
            var extension   = httpContext.Request["extension"];
            var user        = _userService.Authencation(account, password, extension);

            _logger.DebugFormat("正在验证登录信息:{0}", account);
            string redirectUrl;
            bool   isLoginSuccess;
            var    urlReferrer   = httpContext.Request.UrlReferrer;
            var    urlrefInQuery = httpContext.Request["urlReferrer"];
            var    refUrl        = string.IsNullOrEmpty(urlrefInQuery) ? (urlReferrer != null ? urlReferrer.AbsoluteUri : string.Empty) : urlrefInQuery;
            var    loginEntity   = new LoginEntity();

            loginEntity.ReferrerUrl = refUrl;
            if (user != null)
            {
                httpContext.Items[HttpMoudlesConst.HttpUserKey] = user;
                var loginCookie = new HttpCookie(LoginCookieKey, _desCrypto.Encryptor(account))
                {
                    HttpOnly = true
                };
                var loginExtensionCookie = new HttpCookie(LoginExtensionCookieKey, extension)
                {
                    HttpOnly = true
                };
                httpContext.Response.Cookies.Add(loginCookie);
                httpContext.Response.Cookies.Add(loginExtensionCookie);


                _logger.DebugFormat("urlrefInQuery:{0}", urlrefInQuery);
                _logger.DebugFormat("urlReferrer:{0}", urlReferrer);
                if (!string.IsNullOrEmpty(refUrl))
                {
                    if (refUrl.IndexOf(LoginUrl.Replace("~/", ""), StringComparison.CurrentCultureIgnoreCase) >= 0)
                    {
                        refUrl = ConvertUrl(HomeUrl);
                    }
                }
                redirectUrl    = !string.IsNullOrEmpty(refUrl) ? refUrl : ConvertUrl(refUrl);
                isLoginSuccess = true;
            }
            else
            {
                _logger.DebugFormat("用户名密码校验不通过:account={0};pwd={1},跳转到登录页并记录状态", account, password);
                redirectUrl    = LoginUrl + string.Format("?status={0}", "0");
                isLoginSuccess = false;
            }

            loginEntity.RedirectUrl    = redirectUrl;
            loginEntity.Extension      = extension;
            loginEntity.UserName       = account;
            loginEntity.Pwd            = password;
            loginEntity.IsLoginSuccess = isLoginSuccess;

            foreach (var handler in _systemAuthenticationHandlers)
            {
                handler.OnLoginEnd(loginEntity);
            }
            foreach (var handler in _customAuthenticationHandlers)
            {
                handler.OnLoginEnd(loginEntity);
            }
            httpContext.Response.Redirect(redirectUrl);
        }
        /// <summary>
        /// Performs the actual conversion.
        /// </summary>
        /// <param name="FromContentType">Content type of the content to convert from.</param>
        /// <param name="From">Stream pointing to binary representation of content.</param>
        /// <param name="FromFileName">If the content is coming from a file, this parameter contains the name of that file.
        /// Otherwise, the parameter is the empty string.</param>
        /// <param name="ResourceName">Local resource name of file, if accessed from a web server.</param>
        /// <param name="URL">URL of resource, if accessed from a web server.</param>
        /// <param name="ToContentType">Content type of the content to convert to.</param>
        /// <param name="To">Stream pointing to where binary representation of content is to be sent.</param>
        /// <param name="Session">Session states.</param>
        /// <returns>If the result is dynamic (true), or only depends on the source (false).</returns>
        public bool Convert(string FromContentType, Stream From, string FromFileName, string ResourceName, string URL, string ToContentType,
                            Stream To, Variables Session)
        {
            HttpRequest Request = null;
            string      Markdown;
            bool        b;

            using (StreamReader rd = new StreamReader(From))
            {
                Markdown = rd.ReadToEnd();
            }

            if (Session != null && Session.TryGetVariable("Request", out Variable v))
            {
                Request = v.ValueObject as HttpRequest;

                if (Request != null)
                {
                    int i = Markdown.IndexOf("\r\n\r\n");
                    if (i < 0)
                    {
                        i = Markdown.IndexOf("\n\n");
                    }

                    if (i > 0)
                    {
                        string Header = Markdown.Substring(0, i);
                        string Parameter;

                        foreach (string Row in Header.Split(CommonTypes.CRLF, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (!Row.StartsWith("Parameter:", StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            Parameter = Row.Substring(10).Trim();
                            if (Request.Header.TryGetQueryParameter(Parameter, out string Value))
                            {
                                Value = System.Net.WebUtility.UrlDecode(Value);
                                if (double.TryParse(Value.Replace(".", System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator), out double d))
                                {
                                    Session[Parameter] = d;
                                }
                                else if (bool.TryParse(Value, out b))
                                {
                                    Session[Parameter] = b;
                                }
                                else
                                {
                                    Session[Parameter] = Value;
                                }
                            }
                            else
                            {
                                Session[Parameter] = string.Empty;
                            }
                        }
                    }
                }
            }

            MarkdownSettings Settings = new MarkdownSettings(emojiSource, true, Session)
            {
                RootFolder = rootFolder
            };

            if (!string.IsNullOrEmpty(bareJid))
            {
                Settings.HttpxProxy             = "/HttpxProxy/%URL%";
                Settings.LocalHttpxResourcePath = "httpx://" + bareJid + "/";
            }

            MarkdownDocument Doc = new MarkdownDocument(Markdown, Settings, FromFileName, ResourceName, URL, typeof(HttpException));
            IUser            User;

            if (Doc.TryGetMetaData("UserVariable", out KeyValuePair <string, bool>[] MetaValues))
            {
                bool Authorized = true;

                if (!Doc.TryGetMetaData("Login", out KeyValuePair <string, bool>[] Login))
                {
                    Login = null;
                }

                if (!Doc.TryGetMetaData("Privilege", out KeyValuePair <string, bool>[] Privilege))
                {
                    Privilege = null;
                }

                foreach (KeyValuePair <string, bool> P in MetaValues)
                {
                    if (Session is null)
                    {
                        Authorized = false;
                        break;
                    }

                    if (!Session.TryGetVariable(P.Key, out v))
                    {
                        Uri    LoginUrl      = null;
                        string LoginFileName = null;
                        string FromFolder    = Path.GetDirectoryName(FromFileName);

                        if (Login != null)
                        {
                            foreach (KeyValuePair <string, bool> P2 in Login)
                            {
                                LoginFileName = Path.Combine(FromFolder, P2.Key.Replace('/', Path.DirectorySeparatorChar));
                                LoginUrl      = new Uri(new Uri(URL), P2.Key.Replace(Path.DirectorySeparatorChar, '/'));

                                if (File.Exists(LoginFileName))
                                {
                                    break;
                                }
                                else
                                {
                                    LoginFileName = null;
                                }
                            }
                        }

                        if (LoginFileName != null)
                        {
                            string           LoginMarkdown = File.ReadAllText(LoginFileName);
                            MarkdownDocument LoginDoc      = new MarkdownDocument(LoginMarkdown, Settings, LoginFileName, LoginUrl.AbsolutePath,
                                                                                  LoginUrl.ToString(), typeof(HttpException));

                            if (!Session.TryGetVariable(P.Key, out v))
                            {
                                Authorized = false;
                                break;
                            }
                        }
                        else
                        {
                            Authorized = false;
                            break;
                        }
                    }

                    User = v.ValueObject as IUser;
                    if (User is null)
                    {
                        Authorized = false;
                        break;
                    }

                    if (Privilege != null)
                    {
                        foreach (KeyValuePair <string, bool> P2 in Privilege)
                        {
                            if (!User.HasPrivilege(P2.Key))
                            {
                                Authorized = false;
                                break;
                            }
                        }
                    }

                    if (!Authorized)
                    {
                        break;
                    }
                }

                if (!Authorized)
                {
                    if (Login != null)
                    {
                        foreach (KeyValuePair <string, bool> P in Login)
                        {
                            StringBuilder Location = new StringBuilder(P.Key);
                            if (P.Key.IndexOf('?') >= 0)
                            {
                                Location.Append('&');
                            }
                            else
                            {
                                Location.Append('?');
                            }

                            Location.Append("from=");

                            if (Request != null)
                            {
                                Location.Append(System.Net.WebUtility.UrlEncode(Request.Header.GetURL(true, true)));
                            }
                            else
                            {
                                Location.Append(System.Net.WebUtility.UrlEncode(URL));
                            }

                            throw new TemporaryRedirectException(Location.ToString());
                        }
                    }

                    throw new ForbiddenException();
                }
            }

            if (Doc.TryGetMetaData("AudioControls", out MetaValues))
            {
                foreach (KeyValuePair <string, bool> P in MetaValues)
                {
                    if (CommonTypes.TryParse(P.Key, out b))
                    {
                        Settings.AudioControls = b;
                    }
                }
            }

            if (Doc.TryGetMetaData("AudioAutoplay", out MetaValues))
            {
                foreach (KeyValuePair <string, bool> P in MetaValues)
                {
                    if (CommonTypes.TryParse(P.Key, out b))
                    {
                        Settings.AudioAutoplay = b;
                    }
                }
            }

            if (Doc.TryGetMetaData("VideoControls", out MetaValues))
            {
                foreach (KeyValuePair <string, bool> P in MetaValues)
                {
                    if (CommonTypes.TryParse(P.Key, out b))
                    {
                        Settings.VideoControls = b;
                    }
                }
            }

            if (Doc.TryGetMetaData("VideoAutoplay", out MetaValues))
            {
                foreach (KeyValuePair <string, bool> P in MetaValues)
                {
                    if (CommonTypes.TryParse(P.Key, out b))
                    {
                        Settings.VideoAutoplay = b;
                    }
                }
            }

            if (Session != null && Session.TryGetVariable("Response", out v))
            {
                if (v.ValueObject is HttpResponse Response)
                {
                    Response.SetHeader("X-Content-Type-Options", "nosniff");

                    if (!this.CopyHttpHeader("Cache-Control", Doc, Response))
                    {
                        if (Doc.IsDynamic)
                        {
                            Response.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");
                        }
                        else
                        {
                            Response.SetHeader("Cache-Control", "no-transform,public,max-age=86400,s-maxage=86400");
                        }
                    }

                    this.CopyHttpHeader("Access-Control-Allow-Origin", Doc, Response);
                    this.CopyHttpHeader("Content-Security-Policy", Doc, Response);
                    this.CopyHttpHeader("Public-Key-Pins", Doc, Response);
                    this.CopyHttpHeader("Strict-Transport-Security", Doc, Response);
                    this.CopyHttpHeader("Sunset", Doc, Response);
                    this.CopyHttpHeader("Vary", Doc, Response);
                }
            }

            string HTML = Doc.GenerateHTML();

            byte[] Data = Utf8WithBOM.GetBytes(HTML);
            To.Write(Data, 0, Data.Length);

            return(Doc.IsDynamic);
        }