예제 #1
0
파일: CASUtils.cs 프로젝트: radtek/safeid
        public static CASConnectorBase GetService(DbBase database, Page page, Uri service)
        {
            if (service == null)
            {
                return(new EmptyPlugin());
            }

            String log2 = "";

            if (page.Application["plugins"] == null) //Se por algum motivo não foi adicionado no Global.asax
            {
                page.Application["plugins"] = CASPlugins.GetPlugins2(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data/config"), Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data/plugins"), out log2);
            }

            StringBuilder tmp = new StringBuilder();

            tmp.AppendLine("service = " + service.AbsoluteUri);

            tmp.AppendLine(log2);

            if (page.Application["plugins"] != null)
            {
                tmp.AppendLine("plugins = " + page.Application["plugins"].GetType().ToString());
            }
            else
            {
                tmp.AppendLine("plugins = null");
            }

            List <CASPluginService> plugins = (List <CASPluginService>)page.Application["plugins"];

            tmp.AppendLine("plugins.Count = " + plugins.Count);

            foreach (CASPluginService p in plugins)
            {
                tmp.AppendLine("p = " + p.ToString());

                if (p.Equal(service))
                {
                    try
                    {
                        CASConnectorBase conn = (CASConnectorBase)Activator.CreateInstance(p.Plugin);
                        conn.SetStart(database, service, p.Config.Attributes, p);

                        return(conn);
                    }
                    catch (Exception ex) {
                        Tools.Tool.notifyException(ex, page);
                    }
                }
            }

            Tools.Tool.notifyException(new Exception(tmp.ToString()), page);

            return(new EmptyPlugin());
        }
예제 #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            /*
             * 2.4. /validate [CAS 1.0]
             * /validate checks the validity of a service ticket. /validate is part of the CAS 1.0 protocol and thus does not handle proxy authentication. CAS MUST respond with a ticket validation failure response when a proxy ticket is passed to /validate.
             * 2.4.1. parameters
             * The following HTTP request parameters MAY be specified to /validate. They are case sensitive and MUST all be handled by /validate.
             * service [REQUIRED] - the identifier of the service for which the ticket was issued, as discussed in Section 2.2.1. As a HTTP request parameter, the "service" value MUST be URL-encoded as described in Section 2.2 of RFC 1738 [4].
             * ticket [REQUIRED] - the service ticket issued by /login. Service tickets are described in Section 3.1.
             * renew [OPTIONAL] - if this parameter is set, ticket validation will only succeed if the service ticket was issued from the presentation of the user's primary credentials. It will fail if the ticket was issued from a single sign-on session.
             *
             * 2.4.2. response
             * /validate will return one of the following two responses:
             *
             * On ticket validation success:
             * yes<LF>
             *
             * On ticket validation failure:
             * no<LF>
             *
             * 2.4.3. URL examples of /validate
             * Simple validation attempt:
             * https://cas.example.org/cas/validate?service=http%3A%2F%2Fwww.example.org%2Fservice&ticket=ST-1856339-aA5Yuvrxzpv8Tau1cYQ7
             *
             * Ensure service ticket was issued by presentation of primary credentials:
             * https://cas.example.org/cas/validate?service=http%3A%2F%2Fwww.example.org%2Fservice&ticket=ST-1856339-aA5Yuvrxzpv8Tau1cYQ7&renew=true
             *
             */

            Boolean renew  = (!String.IsNullOrEmpty(Request["renew"]) && (Request["renew"].ToString().ToLower() == "true"));
            String  ticket = (!String.IsNullOrEmpty(Request.QueryString["ticket"]) ? Request.QueryString["ticket"].ToString() : "");

            Page.Response.ContentType     = "text/plain; charset=UTF-8";
            Page.Response.ContentEncoding = Encoding.UTF8;


            Uri svc = null;

            try
            {
                svc = new Uri(Request.QueryString["service"]);
            }
            catch { }

            using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
            {
                CASConnectorBase connector = CASUtils.GetService(db, this, svc);

                if ((connector == null) || (connector is EmptyPlugin))
                {
                    //Ticket não informado
                    Response.Write("no\n");
                }
                else if (connector.Grant(ticket, renew, false).Success)
                {
                    Response.Write("yes\n");
                }
                else
                {
                    Response.Write("no\n");
                }
            }
            Page.Response.Status     = "200 OK";
            Page.Response.StatusCode = 200;
            //Page.Response.OutputStream.Write(bRet, 0, bRet.Length);
            //Page.Response.OutputStream.Flush();
        }
예제 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"/cas/login/?" + Request.QueryString + "\"><div class=\"login_form\">";


            Uri svc = null;

            try
            {
                svc = new Uri(Request.QueryString["service"]);
            }
            catch { }

            using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
            {
                CASConnectorBase connector = CASUtils.GetService(db, this, null);

                if (connector == null)//Nunca deve ser nulo, em caso de não encontrado deve retornar um Emptylugin
                {
                    //Serviço não informado ou não encontrado
                    html += "    <ul>";
                    html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_invalid_uri") + "</div>";
                    html += "    </ul>";
                }
                else
                {
                    String ticket = (!String.IsNullOrEmpty(Request.QueryString["ticket"]) ? Request.QueryString["ticket"].ToString() : "");
                    connector.DestroyTicket(ticket, null);

                    HttpCookie tgc = Request.Cookies["TGC-SafeID"];
                    if (tgc != null)
                    {
                        connector.DestroyTicket(tgc);
                    }

                    try
                    {
                        Response.Cookies.Remove("TGC-SafeID");
                        Response.Cookies.Remove("TGT-SafeID");
                    }
                    catch { }

                    try
                    {
                        //Adiciona o cookie do TGC
                        HttpCookie cookie = new HttpCookie("TGC-SafeID");
                        //cookie.Domain = page.Request.Url.Host;
                        cookie.Path  = "/cas";
                        cookie.Value = "none";

                        cookie.Expires = DateTime.Now.AddDays(-30);

                        //Adiciona o cookie
                        Response.Cookies.Add(cookie);
                    }
                    catch { }

                    try
                    {
                        //Adiciona o cookie do TGC
                        HttpCookie cookie = new HttpCookie("TGT-SafeID");
                        //cookie.Domain = page.Request.Url.Host;
                        cookie.Path  = "/cas";
                        cookie.Value = "none";

                        cookie.Expires = DateTime.Now.AddDays(-30);

                        //Adiciona o cookie
                        Response.Cookies.Add(cookie);
                    }
                    catch { }


                    error = MessageResource.GetMessage("logout_text");
                    String url = (!String.IsNullOrEmpty(Request.QueryString["url"]) ? Request.QueryString["url"].ToString() : "");
                    try
                    {
                        Uri tmp = new Uri(url);
                        error = "<a href=\"" + tmp.AbsoluteUri + "\">" + String.Format(MessageResource.GetMessage("logout_text_url"), tmp.AbsoluteUri) + "</a>";
                    }
                    catch { }

                    if (String.IsNullOrEmpty(url) && svc != null)
                    {
                        Response.Redirect(svc.AbsoluteUri, false);
                        return;
                    }

                    html += "    <ul>";
                    if (error != "")
                    {
                        html += "        <li><div class=\"error-box\">" + error + "</div>";
                    }
                    html += "        </li>";
                    html += "    </ul>     ";
                }

                html += "</div></form>";
            }
            holderContent.Controls.Add(new LiteralControl(html));
        }
예제 #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Boolean renew   = (!String.IsNullOrEmpty(Request["renew"]) && (Request["renew"].ToString().ToLower() == "true"));
            Boolean gateway = (!String.IsNullOrEmpty(Request["gateway"]) && (Request["gateway"].ToString().ToLower() == "true"));
            Boolean warn    = (!String.IsNullOrEmpty(Request["warn"]) && (Request["warn"].ToString().ToLower() == "true"));

            if (renew || warn)
            {
                gateway = false;
            }

            if (warn)
            {
                renew = true;
            }

            String html  = "";
            String error = "";

            html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"/cas/login/?" + Request.QueryString + "\"><div class=\"login_form\">";

            try
            {
                Session.Remove("cas_ticket");
            }
            catch { }


            Uri svc = null;

            try
            {
                svc = new Uri(Request.QueryString["service"]);
            }
            catch { }

            using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
            {
                CASConnectorBase connector = CASUtils.GetService(db, this, svc);

                if ((connector == null) || (connector is EmptyPlugin))
                {
                    //Serviço não informado ou não encontrado
                    html += "    <ul>";
                    html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_invalid_uri") + "</div>";
                    html += "    </ul>";
                }
                else
                {
                    if (Request.HttpMethod == "GET")
                    {
                        //Serviço encontrado

                        //verifica se há cookie com token
                        HttpCookie tgc = Request.Cookies["TGC-SafeID"];
                        if (tgc != null)
                        {
                            //Verifica autenticação através do cookie
                            if (connector.Grant(tgc, renew, warn).Success)
                            {
                                Redirect(tgc.Value);//Autenticado redireciona
                                return;
                            }
                        }
                        else if (gateway)//é Gateway, ou seja não mostra opção do usuário digitar a senha
                        {
                            Redirect("");
                            return;
                        }
                    }
                    else
                    {
                        //Valida usuário e senha
                        try
                        {
                            if (String.IsNullOrEmpty(Request["username"]) || String.IsNullOrEmpty(Request["password"]))
                            {
                                error = MessageResource.GetMessage("valid_username_pwd");
                            }
                            else
                            {
                                CASTicketResult casTicket = connector.Grant(Request["username"], Request["password"]);
                                CASUtils.ClearCookie(Page);
                                if ((casTicket.Success) && (casTicket.ChangePasswordNextLogon))
                                {
                                    //Cria a sessão com as informações necessárias e redireciona
                                    Session["cas_ticket"] = casTicket;
                                    Response.Redirect(Session["ApplicationVirtualPath"] + "cas/changepassword/", false);
                                    return;
                                }
                                else if (casTicket.Success)
                                {
                                    connector.SaveTicket(casTicket);//Salva o token recebido

                                    //Salva o token no cookie
                                    CASUtils.AddCoockie(this, casTicket);

                                    Redirect(casTicket.GrantTicket);//Autenticação OK redireciona
                                    return;
                                }
                                else
                                {
                                    error = casTicket.ErrorText;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                            Tools.Tool.notifyException(ex);
                            error = MessageResource.GetMessage("internal_error");
                        }
                    }

                    html += "    <ul>";
                    html += "        <li>";
                    html += "            <span class=\"inputWrap\">";
                    html += "				<input type=\"text\" id=\"username\" tabindex=\"1\" name=\"username\" value=\""+ Request["username"] + "\" style=\"\" placeholder=\"" + MessageResource.GetMessage("login_user_name") + "\" onfocus=\"$('#username').addClass('focus');\" onblur=\"$('#username').removeClass('focus');\" />";
                    html += "				<span id=\"ph_usernameIcon\" onclick=\"$('#username').focus();\"></span>";
                    html += "            </span>";
                    html += "        </li>";
                    html += "        <li>";
                    html += "            <span class=\"inputWrap\">";
                    html += "				<input type=\"password\" id=\"password\" tabindex=\"2\" name=\"password\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("login_password") + "\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
                    html += "				<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                    html += "			</span>";
                    html += "        </li>";
                    if (error != "")
                    {
                        html += "        <li><div class=\"error-box\">" + error + "</div>";
                    }
                    html += "        </li>";
                    html += "        <li>";
                    html += "            <span class=\"forgot\"> <a href=\"" + Session["ApplicationVirtualPath"] + "cas/recover/?service=" + HttpUtility.UrlEncode(connector.Service.AbsoluteUri) + "\">" + MessageResource.GetMessage("login_forgot") + "</a> </span>";
                    html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("login_log") + "</button>";
                    html += "        </li>";
                    html += "    </ul>     ";
                }

                html += "</div></form>";
            }

            holderContent.Controls.Add(new LiteralControl(html));
        }
예제 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            html += "<div id=\"recover_container\"><form id=\"serviceRecover\" name=\"serviceRecover\" method=\"post\"><div class=\"login_form\">";

            Uri svc = null;

            try
            {
                svc = new Uri(Request.QueryString["service"]);
            }
            catch { }

            using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
            {
                CASConnectorBase connector = CASUtils.GetService(db, this, svc);

                if ((connector == null) || (connector is EmptyPlugin))
                {
                    //Serviço não informado ou não encontrado
                    html += "    <ul>";
                    html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_invalid_uri") + "</div>";
                    html += "    </ul>";
                }
                else if ((connector.State != null) && (connector.State is CASPluginService) && !(((CASPluginService)connector.State).Config.PermitPasswordRecover))
                {
                    CASPluginService p = (CASPluginService)connector.State;

                    //Serviço não informado ou não encontrado
                    html += "    <ul>";
                    html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_not_permit_recover_pwd") + (!String.IsNullOrEmpty(p.Config.Admin) ? "<br /><br />" + p.Config.Admin : "") + "</div>";
                    html += "    </ul>";
                }
                else
                {
                    //Caso a recuperação de senha seja externa, redireciona
                    if ((connector.State is CASPluginService) && (((CASPluginService)connector.State).Config.ExternalPasswordRecover) && (((CASPluginService)connector.State).Config.PasswordRecoverUri != null))
                    {
                        Response.Redirect(((CASPluginService)connector.State).Config.PasswordRecoverUri.AbsoluteUri, false);
                        return;
                    }

                    Session["recover_service"] = svc.AbsoluteUri;

                    if (Request.HttpMethod == "POST")
                    {
                        try
                        {
                            CASUserInfo user = connector.FindUser(Request["username"]);
                            user.Service = connector.Service;
                            if ((user.Success) && (user.Emails != null) && (user.Emails.Count > 0))
                            {
                                user.NewCode();
                                Session["user_info"] = user;

                                Response.Redirect("/cas/recover/step1/", false);
                                return;
                            }
                            else if ((user.Emails == null) || (user.Emails.Count == 0))
                            {
                                error = MessageResource.GetMessage("user_email_list");
                            }
                            else
                            {
                                error = user.ErrorText;
                            }
                        }
                        catch (Exception ex)
                        {
                            Tools.Tool.notifyException(ex);
                            error = MessageResource.GetMessage("internal_error");
                        }
                    }

                    html += "    <input type=\"hidden\" name=\"do\" value=\"recover1\" />";
                    html += "    <ul>";
                    html += "        <li>";
                    html += "            <p style=\"width:270px;padding:0 0 20px 0;color:#000;\">" + MessageResource.GetMessage("login_recover_message") + "</p>";
                    html += "        </li>";
                    html += "        <li>";
                    html += "            <span class=\"inputWrap\">";
                    //html += "			    <span id=\"ph_userLogin\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("login_user_name") + "</span>";
                    html += "			    <input type=\"text\" id=\"username\" tabindex=\"1\" name=\"username\" value=\"\" style=\"\"  placeholder=\""+ MessageResource.GetMessage("login_user_name") + "\" onfocus=\"$('#userLogin').addClass('focus');\" onblur=\"$('#userLogin').removeClass('focus');\" />";
                    html += "			    <span id=\"ph_usernameIcon\" onclick=\"$('#userLogin').focus();\"></span>";
                    html += "            </span>";
                    html += "        </li>";
                    if (error != "")
                    {
                        html += "        <li><div class=\"error-box\">" + error + "</div>";
                    }
                    html += "        <li>";
                    html += "            <span class=\"forgot\"> <a href=\"" + svc.AbsoluteUri + "\">" + MessageResource.GetMessage("cancel") + "</a> " + MessageResource.GetMessage("or") + " </span>";
                    html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("login_recover_btn_recover") + "</button>";
                    html += "        </li>";
                    html += "    </ul>     ";
                }

                html += "</div>";
                html += "</form>";
                html += "</div>";
            }

            holderContent.Controls.Add(new LiteralControl(html));
        }
예제 #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            html += "<div id=\"recover_container\"><form id=\"serviceRecover\" name=\"serviceRecover\" method=\"post\"><div class=\"login_form\">";

            if (Session["user_info"] == null || !(Session["user_info"] is CASUserInfo))
            {
                //Serviço não informado ou não encontrado
                html += "    <ul>";
                html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("invalid_session") + "</div>";
                html += "    </ul>";
            }
            else
            {
                CASUserInfo userInfo = (CASUserInfo)Session["user_info"];
                using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
                {
                    CASConnectorBase connector = CASUtils.GetService(db, this, userInfo.Service);

                    if ((connector == null) || (connector is EmptyPlugin))
                    {
                        //Serviço não informado ou não encontrado
                        html += "    <ul>";
                        html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_invalid_uri") + "</div>";
                        html += "    </ul>";
                    }
                    if ((userInfo.RecoveryCode == null) || (String.IsNullOrEmpty((String)Session["userCode"])))
                    {
                        html += "    <ul>";
                        html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("invalid_session") + "</div>";
                        html += "    </ul>";
                    }
                    else
                    {
                        if (Request.HttpMethod == "POST")
                        {
                            try
                            {
                                //String pwd = Session["atual_password"].ToString();

                                String password  = Tools.Tool.TrataInjection(Request["password"]);
                                String password2 = Request["password2"];

                                if ((password == null) || (password == ""))
                                {
                                    error = MessageResource.GetMessage("type_password");
                                }
                                else if ((password2 == null) || (password2 == ""))
                                {
                                    error = MessageResource.GetMessage("type_password_confirm");
                                }
                                else if (password != password2)
                                {
                                    error = MessageResource.GetMessage("password_not_equal");
                                }
                                else
                                {
                                    CASChangePasswordResult res = connector.ChangePassword(userInfo, password);
                                    if (res.Success)
                                    {
                                        Response.Redirect(Session["ApplicationVirtualPath"] + "cas/passwordchanged/", false);
                                        return;
                                    }
                                    else
                                    {
                                        if (res.ErrorText == null)
                                        {
                                            throw new Exception("");
                                        }

                                        error = res.ErrorText;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Tools.Tool.notifyException(ex);
                                error = MessageResource.GetMessage("internal_error");
                            }
                        }

                        html += "<ul>";
                        html += "    <li>";
                        html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("new_password_title") + "</p>";
                        html += "    </li>";
                        html += "    <li>";
                        html += "        <span class=\"inputWrap\">";
                        html += "			<input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password") + "\" onkeyup=\"cas.passwordStrength('#password');\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
                        html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                        html += "        </span>";
                        html += "    </li>";
                        html += "    <li>";
                        html += "        <span class=\"inputWrap\">";
                        html += "			<input type=\"password\" id=\"password2\" tabindex=\"1\" name=\"password2\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password_confirm") + "\" onfocus=\"$('#password2').addClass('focus');\" onblur=\"$('#password2').removeClass('focus');\" />";
                        html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password2').focus();\"></span>";
                        html += "        </span>";
                        html += "    </li>";
                        html += "    <li>";
                        html += "        <div id=\"passwordStrength\"><span>" + MessageResource.GetMessage("password_strength") + ": " + MessageResource.GetMessage("unknow") + "</span><div class=\"bar\"></div></div>";
                        html += "    </li>";

                        if (error != "")
                        {
                            html += "        <li><div class=\"error-box\">" + error + "</div>";
                        }

                        html += "    <li>";
                        html += "        <span class=\"forgot\"> <a href=\"" + userInfo.Service.AbsoluteUri + "\">" + MessageResource.GetMessage("cancel") + "</a> " + MessageResource.GetMessage("or") + " </span>";
                        html += "        <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("change_password") + "</button>";
                        html += "    </li>";
                        html += "</ul>     ";
                    }
                }

                html += "</div>";
                html += "</form>";
                html += "</div>";
            }
            holderContent.Controls.Add(new LiteralControl(html));
        }
예제 #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            /*2.5. /serviceValidate [CAS 2.0]
             *
             * /serviceValidate checks the validity of a service ticket and returns an XML-fragment response. /serviceValidate MUST also generate and issue proxy-granting tickets when requested. /serviceValidate MUST NOT return a successful authentication if it receives a proxy ticket. It is RECOMMENDED that if /serviceValidate receives a proxy ticket, the error message in the XML response SHOULD explain that validation failed because a proxy ticket was passed to /serviceValidate.
             *
             * 2.5.1. parameters
             * The following HTTP request parameters MAY be specified to /serviceValidate. They are case sensitive and MUST all be handled by /serviceValidate.
             * service [REQUIRED] - the identifier of the service for which the ticket was issued, as discussed in Section 2.2.1. As a HTTP request parameter, the "service" value MUST be URL-encoded as described in Section 2.2 of RFC 1738 [4].
             * ticket [REQUIRED] - the service ticket issued by /login. Service tickets are described in Section 3.1.
             * pgtUrl [OPTIONAL] - the URL of the proxy callback. Discussed in Section 2.5.4. As a HTTP request parameter, the "pgtUrl" value MUST be URL-encoded as described in Section 2.2 of RFC 1738 [4].
             * renew [OPTIONAL] - if this parameter is set, ticket validation will only succeed if the service ticket was issued from the presentation of the user's primary credentials. It will fail if the ticket was issued from a single sign-on session.
             *
             * 2.5.2. response
             * /serviceValidate will return an XML-formatted CAS serviceResponse as described in the XML schema in Appendix A. Below are example responses:
             *
             * On ticket validation success:
             * <cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
             * <cas:authenticationSuccess>
             * <cas:user>username</cas:user>
             * <cas:proxyGrantingTicket>PGTIOU-84678-8a9d...</cas:proxyGrantingTicket>
             * </cas:authenticationSuccess>
             * </cas:serviceResponse>
             *
             * On ticket validation failure:
             * <cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
             * <cas:authenticationFailure code="INVALID_TICKET">
             *  Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized`
             * </cas:authenticationFailure>
             * </cas:serviceResponse>
             *
             * For proxy responses, see section 2.6.2.
             *
             * 2.5.3. error codes
             * The following values MAY be used as the "code" attribute of authentication failure responses. The following is the minimum set of error codes that all CAS servers MUST implement. Implementations MAY include others.
             * INVALID_REQUEST - not all of the required request parameters were present
             * INVALID_TICKET_SPEC - failure to meet the requirements of validation specification
             * UNAUTHORIZED_SERVICE_PROXY - the service is not authorized to perform proxy authentication
             * INVALID_PROXY_CALLBACK - The proxy callback specified is invalid. The credentials specified for proxy authentication do not meet the security requirements
             * INVALID_TICKET - the ticket provided was not valid, or the ticket did not come from an initial login and "renew" was set on validation. The body of the <cas:authenticationFailure> block of the XML response SHOULD describe the exact details.
             * INVALID_SERVICE - the ticket provided was valid, but the service specified did not match the service associated with the ticket. CAS MUST invalidate the ticket and disallow future validation of that same ticket.
             * INTERNAL_ERROR - an internal error occurred during ticket validation
             *
             * For all error codes, it is RECOMMENDED that CAS provide a more detailed message as the body of the <cas:authenticationFailure> block of the XML response.
             */

            Boolean renew  = (!String.IsNullOrEmpty(Request["renew"]) && (Request["renew"].ToString().ToLower() == "true"));
            String  ticket = (!String.IsNullOrEmpty(Request.QueryString["ticket"]) ? Request.QueryString["ticket"].ToString() : "");

            Page.Response.ContentType     = "application/xml; charset=UTF-8";
            Page.Response.ContentEncoding = Encoding.UTF8;

            try
            {
                Uri svc = null;
                try
                {
                    svc = new Uri(Request.QueryString["service"]);
                }
                catch { }

                using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
                {
                    CASConnectorBase connector = CASUtils.GetService(db, this, svc);

                    if (svc == null)
                    {
                        //Serviço não informado ou não encontrado
                        Response.Write(getError(retCode.INVALID_REQUEST, "Service"));
                    }
                    else if ((connector == null) || (connector is EmptyPlugin))
                    {
                        //Serviço não informado ou não encontrado
                        Response.Write(getError(retCode.INVALID_SERVICE, svc.AbsoluteUri));
                    }
                    else if (ticket == "")
                    {
                        //Ticket não informado
                        Response.Write(getError(retCode.INVALID_REQUEST, "Ticket"));
                    }
                    else
                    {
                        CASTicketResult loginRes = connector.Grant(ticket, renew, false);
                        if (loginRes.Success)
                        {
                            StringBuilder xml = new StringBuilder();

                            xml.AppendLine("<cas:serviceResponse xmlns:cas=\"http://www.yale.edu/tp/cas\">");
                            xml.AppendLine("  <cas:authenticationSuccess>");
                            xml.AppendLine("    <cas:user>" + loginRes.UserName + "</cas:user>");
                            if ((loginRes.Attributes != null) && (loginRes.Attributes.Count > 0))
                            {
                                xml.AppendLine("    <cas:attributes>");
                                foreach (String key in loginRes.Attributes.Keys)
                                {
                                    xml.AppendLine("        <cas:" + key + ">" + loginRes.Attributes[key] + "</cas:" + key + ">");
                                }

                                xml.AppendLine("    </cas:attributes>");
                            }
                            xml.AppendLine("    <cas:proxyGrantingTicket>" + ticket + "</cas:proxyGrantingTicket>");
                            xml.AppendLine("  </cas:authenticationSuccess>");
                            xml.AppendLine("</cas:serviceResponse>");

                            Response.Write(xml.ToString());
                        }
                        else
                        {
                            Response.Write(getError(retCode.INVALID_TICKET, ticket));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                getError(retCode.INTERNAL_ERROR, "");
            }

            Page.Response.Status     = "200 OK";
            Page.Response.StatusCode = 200;
            //Page.Response.OutputStream.Write(bRet, 0, bRet.Length);
            //Page.Response.OutputStream.Flush();
        }
예제 #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            html += "<div id=\"recover_container\"><form id=\"pwdChange\" name=\"pwdChange\" method=\"post\"><div class=\"login_form\">";

            if ((Session["cas_ticket"] == null) || !(Session["cas_ticket"] is CASTicketResult))
            {
                //Serviço não informado ou não encontrado
                html += "    <ul>";
                html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("invalid_session") + "</div>";
                html += "    </ul>";
            }
            else
            {
                CASTicketResult ticket = (CASTicketResult)Session["cas_ticket"];
                using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
                {
                    CASConnectorBase connector = CASUtils.GetService(db, this, ticket.Service);

                    if ((connector == null) || (connector is EmptyPlugin))
                    {
                        //Serviço não informado ou não encontrado
                        html += "    <ul>";
                        html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_invalid_uri") + "</div>";
                        html += "    </ul>";
                    }
                    else if ((connector.State != null) && (connector.State is CASPluginService) && !(((CASPluginService)connector.State).Config.PermitChangePassword))
                    {
                        CASPluginService p = (CASPluginService)connector.State;
                        //Serviço não informado ou não encontrado
                        html += "    <ul>";
                        html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_not_permit_change_pwd") + (!String.IsNullOrEmpty(p.Config.Admin) ? "<br /><br />" + p.Config.Admin : "") + "</div>";
                        html += "    </ul>";
                    }
                    else
                    {
                        if (Request.HttpMethod == "POST")
                        {
                            try
                            {
                                String password  = Tools.Tool.TrataInjection(Request["password"]);
                                String password2 = Request["password2"];
                                if ((password == null) || (password == ""))
                                {
                                    error = MessageResource.GetMessage("type_password");
                                }
                                else if ((password2 == null) || (password2 == ""))
                                {
                                    error = MessageResource.GetMessage("type_password_confirm");
                                }
                                else if (password != password2)
                                {
                                    error = MessageResource.GetMessage("password_not_equal");
                                }
                                else
                                {
                                    CASChangePasswordResult res = connector.ChangePassword(ticket, password);
                                    if (res.Success)
                                    {
                                        connector.SaveTicket(ticket);

                                        CASUtils.AddCoockie(this, ticket);

                                        Session["user_info"] = new CASUserInfo(ticket);

                                        Response.Redirect(Session["ApplicationVirtualPath"] + "cas/passwordchanged/", false);
                                        return;
                                    }
                                    else
                                    {
                                        if (res.ErrorText == null)
                                        {
                                            throw new Exception("");
                                        }

                                        error = res.ErrorText;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Tools.Tool.notifyException(ex);
                                error = MessageResource.GetMessage("internal_error");
                            }
                        }

                        html += "    <ul>";
                        html += "        <li>";
                        html += "            <p style=\"width:270px;padding:0 0 20px 0;color:#000;\">" + MessageResource.GetMessage("password_expired_text") + "</p>";
                        html += "        </li>";
                        html += "    <li>";
                        html += "        <span class=\"inputWrap\">";
                        html += "			<input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\"  placeholder=\""+ MessageResource.GetMessage("new_password") + "\" onkeyup=\"cas.passwordStrength('#password');\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
                        html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                        html += "        </span>";
                        html += "    </li>";
                        html += "    <li>";
                        html += "        <span class=\"inputWrap\">";
                        html += "			<input type=\"password\" id=\"password2\" tabindex=\"1\" name=\"password2\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password_confirm") + "\" onfocus=\"$('#password2').addClass('focus');\" onblur=\"$('#password2').removeClass('focus');\" />";
                        html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password2').focus();\"></span>";
                        html += "        </span>";
                        html += "    </li>";
                        html += "    <li>";
                        html += "        <div id=\"passwordStrength\"><span>" + MessageResource.GetMessage("password_strength") + ": " + MessageResource.GetMessage("unknow") + "</span><div class=\"bar\"></div></div>";
                        html += "    </li>";

                        if (error != "")
                        {
                            html += "        <li><div class=\"error-box\">" + error + "</div>";
                        }

                        html += "        <li>";
                        html += "           <span class=\"forgot\"> <a href=\"" + Session["ApplicationVirtualPath"] + "cas/login/?service=" + HttpUtility.UrlEncode(connector.Service.AbsoluteUri) + "\">" + MessageResource.GetMessage("cancel") + "</a> </span>";
                        html += "           <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("change_password") + "</button>";
                        html += "        </li>";
                        html += "    </ul>";
                    }
                }

                html += "</div>";
                html += "</form>";
                html += "</div>";
            }
            holderContent.Controls.Add(new LiteralControl(html));
        }