Example #1
0
        protected async override Task <string> AuthenticateWithThirdPartyApp(HttpRequestMessage request)
        {
            //从Url中获取授权码
            string authorizationCode = request.GetQueryNameValuePairs().Last(s => s.Key.Equals("code") && !string.IsNullOrEmpty(s.Value)).Value;

            string redirectUri = request.GetQueryNameValuePairs().Last(s => s.Key.Equals("redirectUri") && !string.IsNullOrEmpty(s.Value)).Value;

            //根据授权码获取Token
            EnhancedUriBuilder uriBuilder = new EnhancedUriBuilder(oauth_token_uri);

            uriBuilder.QueryItems.Add("client_id", client_id);
            uriBuilder.QueryItems.Add("redirect_uri", Uri.EscapeUriString(redirectUri));
            uriBuilder.QueryItems.Add("client_secret", client_secret);
            uriBuilder.QueryItems.Add("code", authorizationCode);
            string accessTokenUrl      = uriBuilder.ToString();
            string accessTokenResponse = await Client.GetStringAsync(accessTokenUrl);

            List <KeyValuePair <string, string> > items = CreateItemsFromUriQuery(accessTokenResponse);
            string accessToken = items.SingleOrDefault(s => s.Key.Equals("access_token")).Value;

            //根据Token获取用户登录名
            uriBuilder = new EnhancedUriBuilder(oauth_profile_uri);
            uriBuilder.QueryItems.Add("access_token", accessToken);
            string profileUrl      = uriBuilder.ToString();
            string profileResponse = await Client.GetStringAsync(profileUrl);

            ProfileModel profile = Newtonsoft.Json.JsonConvert.DeserializeObject <ProfileModel>(profileResponse);
            string       id      = profile.id;

            return(id);
        }
        public string GetPassword()
        {
            string password = null;

            EnhancedUriBuilder clearPassUri = new EnhancedUriBuilder(CasAuthentication.CasServerUrlPrefix);

            clearPassUri.Path += "clearPass";

            string clearPassUrl = clearPassUri.Uri.AbsoluteUri;
            string proxyTicket  = CasAuthentication.GetProxyTicketIdFor(clearPassUrl);

            if (string.IsNullOrEmpty(proxyTicket))
            {
                throw new HttpException("Unable to obtain CAS Proxy Ticket for clearPass.");
            }

            string clearPassResponse = null;

            try
            {
                clearPassUri.QueryItems.Add(CasClientConfiguration.Config.ArtifactParameterName, proxyTicket);

                string clearPassRequest = clearPassUri.Uri.AbsoluteUri;
                clearPassResponse = HttpUtil.PerformHttpGet(clearPassRequest, true);
            }
            catch (Exception e)
            {
                throw new HttpException("Unable to obtain clearPass response from CAS. Review CAS logs and ensure the proxy chain is configured correctly.", e);
            }

            if (string.IsNullOrEmpty(clearPassResponse))
            {
                throw new HttpException("No response for clearPass is received from CAS");
            }

            using (TextReader stringReader = new StringReader(clearPassResponse))
            {
                XmlReaderSettings xmlReaderSetting = new XmlReaderSettings();
                xmlReaderSetting.ConformanceLevel = ConformanceLevel.Auto;
                xmlReaderSetting.IgnoreWhitespace = true;
                using (XmlReader xmlReader = XmlReader.Create(stringReader, xmlReaderSetting))
                {
                    if (xmlReader.ReadToFollowing("cas:credentials"))
                    {
                        password = xmlReader.ReadElementString();
                        if (String.IsNullOrEmpty(password))
                        {
                            throw new HttpException("No password was received from CAS. Review clearPass configuration for CAS and ensure the feature is turned on");
                        }
                    }
                }
            }

            return(password);
        }
Example #3
0
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     if (filterContext.RequestContext.HttpContext.Request.Cookies["SSO_Ticket"] != null)
     {
         if (CacheHelper.GetCache(filterContext.RequestContext.HttpContext.Request.Cookies["SSO_Ticket"].Value) != null)
         {
             var backUrl = filterContext.RequestContext.HttpContext.Request["backUrl"];
             if (backUrl != null)
             {
                 EnhancedUriBuilder uriBuilder = new EnhancedUriBuilder(backUrl);
                 uriBuilder.QueryItems["ticket"] = CookieHelper.GetCookie("SSO_Ticket").ToString();
                 backUrl = uriBuilder.Uri.ToString();
             }
             else
             {
                 backUrl = "/Home/Index";
             }
             filterContext.Result = new RedirectResult(backUrl);
         }
     }
     base.OnActionExecuting(filterContext);
 }
        /// <summary>
        /// The implementation uses the CAS clearPass extension to obtain the user's password
        /// by requesting a proxy ticket for clearPass and parsing out the user's password that
        /// is returned as part of the response enclosed within <![CDATA[<cas:credentials>]]> elements.
        /// Returned object is a SecureString.
        /// </summary>
        public SecureString GetSecurePassword()
        {
            EnhancedUriBuilder clearPassUri = new EnhancedUriBuilder(CasAuthentication.CasServerUrlPrefix);

            clearPassUri.Path += "clearPass";

            string proxyTicket = CasAuthentication.GetProxyTicketIdFor(clearPassUri.Uri.AbsoluteUri);

            if (string.IsNullOrEmpty(proxyTicket))
            {
                throw new HttpException("Unable to obtain CAS Proxy Ticket for clearPass.");
            }

            clearPassUri.QueryItems.Add(CasClientConfiguration.Config.ArtifactParameterName, proxyTicket);

            var secureClearPassResponse = new SecureString();

            try
            {
                var body = String.Format(CasClientConfiguration.Config.ClearPassGetRequest, clearPassUri.Uri.PathAndQuery, clearPassUri.Uri.Authority);

                secureClearPassResponse = SecureClient.SecureHttpRequest(clearPassUri.Uri, body, 2000);

                if (secureClearPassResponse.Length == 0)
                {
                    throw new HttpException("ClearPass service returned an empty response.");
                }
            }
            catch (Exception e)
            {
                throw new HttpException(
                          "Unable to obtain clearPass response from CAS. Review CAS logs and ensure the proxy chain is configured correctly.",
                          e);
            }

            // Marshall into plaintext and return final
            var securePassword = new SecureString();

            // Setup pinned variables in memory
            var insecureClearPassResponse = "";
            var insecurePassword          = "";
            var unmanagedString           = IntPtr.Zero;

            var gcHandler  = GCHandle.Alloc(insecureClearPassResponse, GCHandleType.Pinned);
            var pwHandler  = GCHandle.Alloc(insecurePassword, GCHandleType.Pinned);
            var ptrHandler = GCHandle.Alloc(unmanagedString, GCHandleType.Pinned);

            try
            {
                var xmlReaderSetting = new XmlReaderSettings
                {
                    ConformanceLevel = ConformanceLevel.Auto,
                    IgnoreWhitespace = true
                };

                unmanagedString           = Marshal.SecureStringToGlobalAllocUnicode(secureClearPassResponse);
                insecureClearPassResponse = Marshal.PtrToStringUni(unmanagedString);

                if (insecureClearPassResponse == null)
                {
                    throw new AccessViolationException("ClearPass response was erased from memory.");
                }

                using (TextReader stringReader = new StringReader(insecureClearPassResponse))
                {
                    using (var xmlReader = XmlReader.Create(stringReader, xmlReaderSetting))
                    {
                        try
                        {
                            if (xmlReader.ReadToFollowing("cas:credentials"))
                            {
                                insecurePassword = xmlReader.ReadElementString();

                                foreach (char t in insecurePassword)
                                {
                                    securePassword.AppendChar(t);
                                }
                            }

                            if (securePassword.Length == 0)
                            {
                                throw new HttpException(
                                          "No password was received from CAS. Review clearPass configuration for CAS and ensure the feature is turned on");
                            }
                        }
                        finally
                        {
                            // Scrub insecure variables
                            insecurePassword          = null;
                            insecureClearPassResponse = null;

                            // Explicitly close and dispose xmlReader
                            xmlReader.Close();
                            ((IDisposable)xmlReader).Dispose();

                            // Explicitly close and dispose TextReader
                            stringReader.Close();
                            stringReader.Dispose();
                        }
                    }
                }
            }

            // Ensure cleanup
            finally
            {
                pwHandler.Free();
                gcHandler.Free();
                ptrHandler.Free();

                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }

            return(securePassword);
        }
Example #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                FormsAuthenticationTicket formsAuthTicket = CasAuthentication.GetFormsAuthenticationTicket();
                CasAuthenticationTicket   casTicket       = CasAuthentication.ServiceTicketManager.GetTicket(formsAuthTicket.UserData);

                string validateUrl = EnhancedUriBuilder.Combine(CasAuthentication.CasServerUrlPrefix, "proxyValidate");

                Uri    url = new UriBuilder(Request.Url.Scheme, Request.Url.DnsSafeHost, ((Request.IsSecureConnection && Request.Url.Port == 443) || (!Request.IsSecureConnection && Request.Url.Port == 80)) ? -1 : Request.Url.Port, ResolveUrl("DotNetCasProxyDemoApp.application")).Uri;
                string proxyGrantingTicket = casTicket.ProxyGrantingTicket;
                string proxyUrl            = UrlUtil.ConstructProxyTicketRequestUrl(casTicket.ProxyGrantingTicket, url.AbsoluteUri);

                string ticket;
                try
                {
                    ticket = CasAuthentication.GetProxyTicketIdFor(url.AbsoluteUri);
                }
                catch (InvalidOperationException ioe)
                {
                    ticket = "Invalid Request: " + ioe.Message;
                }
                catch (TicketValidationException tve)
                {
                    ticket = "Ticket Exception: " + tve.Message;
                }

                string clickOnceValidation = validateUrl + "?service=" + Server.UrlEncode(url.AbsoluteUri) + "&proxyTicket=" + ticket;
                string appUrl = new UriBuilder(Request.Url.Scheme, Request.Url.DnsSafeHost, Request.Url.Port, ResolveUrl("DotNetCasProxyDemoApp.application"), "?proxyTicket=" + ticket + "&verifyUrl=" + Server.UrlEncode(validateUrl)).Uri.AbsoluteUri;

                StringBuilder debugText = new StringBuilder();
                debugText.AppendLine("Your PGT");
                debugText.AppendLine(proxyGrantingTicket);
                debugText.AppendLine();

                debugText.AppendLine("Target Service URL");
                debugText.AppendLine(url.AbsoluteUri);
                debugText.AppendLine();

                debugText.AppendLine("Proxy Ticket URL");
                debugText.AppendLine(proxyUrl);
                debugText.AppendLine();

                debugText.AppendLine("Proxy Ticket");
                debugText.AppendLine(ticket);
                debugText.AppendLine();

                debugText.AppendLine("Validate URL");
                debugText.AppendLine(validateUrl);
                debugText.AppendLine();

                debugText.AppendLine("ClickOnce URL");
                debugText.AppendLine(appUrl);
                debugText.AppendLine();

                debugText.AppendLine("ClickOnce Validation");
                debugText.AppendLine(clickOnceValidation);

                DebugField.Text   = debugText.ToString();
                ClickOnceUrl.Text = appUrl;
            }
        }