Making Web Services More Efficient


Using the Middle Tier Web Service to Track State

This section discusses ASP.NET Web pages that communicate with the Middle Tier Web Service shown earlier in the chapter. This Web page communicates with the service and uses the values passed back to set an authenticated cookie. This way the Web pages can look for the cookie to see if the user is authorized, rather than having to communicate with the Web Service.

Within a .NET directory that requires form-based security, two files must be present, login.aspx and default.aspx, for this authentication process to work. In addition, modifications need to be made to the web.config file.

Setting up Web.config

When you create a ASP.NET project for C# in Visual Studio.NET, it generates an XML-based file called Web.config. When you open this file, you’ll notice that there are several directives. The following XML shows the different elements that need to be added between the system.web elements.

The authentication element’s mode attribute set to Forms means to use forms-based authentication rather than using Windows or network settings. Within the authorization elements, deny users = "?" tells the ASP.NET application to deny anonymous users.

    <system.web>       <authentication mode="Forms"/>       <authorization>         <deny users="?" />       </authorization>    </system.web>

Creating Login.aspx

The following code sample is an ASP.NET Web page required to appear in a directory that is protected by form-based authentication. Each page in this directory contains the <%@ Import Namespace="System.Web.Security" %> directive, which not only provides access to objects needed for security but also forces each page to examine how security is maintained and then to check for that security method. If someone hasn’t completed a login, the page routes the individual to login.aspx and asks for their credentials. The next import statement makes all the methods from the Web Service available.

Then the HTML begins with defining code within the script tags. This contains one method, Login_Click, which examines the values of the user ID and password sent to the form compared to those found in the XML file. The first step involves creating a ReturnValues object so that the appropriate values are returned from the service. The next step involves creating the object to communicate with the Web Service and then passing the user ID submitted to the form. The information returns all the information, which is probably most efficient for the Web Service, and then the comparison occurs between the XML data and the data in the form.

If the comparison is true, the FormsAuthentication.RedirectFromLoginPage method is called to create the authentication cookie. This first parameter is the variable you wish to use as a unique ID to track the user. Many people use either an e-mail address or a unique number, as in this case. The Boolean, myCookieSetting, tells the method to use a cookie to track the user.

After the script tags, the HTML form is defined. This uses .NET elements seen in other ASP.NET examples shown in previous chapters, but the ASP:RequiredFieldValidator element is new. Both of these ASP directives tell the page that values must be entered for the user ID and password fields.

    <%@ Page language="c#"              Codebehind="WebForm1.aspx.cs"              AutoEventWireup="false"              Inherits="SecurityExample.WebForm1" %>     <%@ Import Namespace="System.Web.Security" %>     <%@ Import Namespace="SecurityExample.localhost" %>     <html>       <script language="C#" runat=server>         void Login_Click(Object sender, EventArgs E) {           ReturnValues myReturnValues = new ReturnValues();           Service1 myService = new Service1();           myReturnValues =           myService.ReturnAll(UserId.Value);           int idResult =           string.Compare(UserId.Value,myReturnValues.id);           int passwordResult = string.Compare          (UserPass.Value,myReturnValues.password);           bool myCookieSetting = true;           if (idResult == passwordResult) {             FormsAuthentication.RedirectFromLoginPage             (myReturnValues.id, myCookieSetting);           } else {             Msg.Text = "Invalid password, -try again";           }         }        </script>      <body>        <form runat=server >         <h3><font face="Verdana">Login Page</font></h3>         <table>           <tr>           <td>UserId:</td>           <td>            <input  type="text"                   runat=server NAME="UserId">           </td>           <td><ASP:RequiredFieldValidator                  ControlToValidate="UserId"                  Display="Static"                  ErrorMessage="*"                  runat=server                                    NAME="myRequiredfieldvalidator1"/>           </td>         </tr>         <tr>           <td>Password:</td>           <td><input                       type=password                      runat=server                      NAME="UserPass"/>           </td>           <td><ASP:RequiredFieldValidator                 ControlToValidate="UserPass"                 Display="Static" ErrorMessage="*"                 runat=server                                  NAME="myRequiredfieldvalidator2"/>           </td>          </tr>         </table>           <asp:button text="Login" OnClick="Login_Click"                       runat=server                        NAME="Button1"/>         <p>           <asp:Label  ForeColor="red"                      Font-Name="Verdana" Font-Size="10"                      runat=server />         </form>        </body>       </html>

Figure 12.6 shows Login.aspx in Internet Explorer.

click to expand
Figure 12.6: Login.aspx in Internet Explorer.

Creating Default.aspx

Default.aspx is the equivalent to index.html for other Web applications. It’s the page the application sends users to when they first come to the directory where the ASP.NET pages reside. Notice in the following code example that this page has the same import statements that the previous example did. This causes the page to check for the security credentials created in the previous example; if it doesn’t find them, the user is sent back to login.aspx. The includes also provide access to the methods in the middle tier Web Service.

Within the script elements reside two methods. The first one, Signout_Click, uses the SignOut() method to delete the user’s authorization cookie and then uses the Response object’s Redirect method to send the user back to login.aspx.

The second method calls the middle tier Web Service created earlier in the chapter. This method uses values sent in from the Web form to call the Web Service and send values back to the appropriate ASP.NET controls on the Web page.

Tip

Using cookie-based authentication prevented this example from making another call to a Web Service to ensure the user is logged in. This is a great way to go when utilizing Web Services because it cuts down on network traffic because the login state is stored on the client.

        <%@ Page language="c#"              Codebehind="default.aspx.cs"              AutoEventWireup="false"              Inherits="SecurityExample._default" %>         <%@ Import Namespace="System.Web.Security " %>         <%@ Import Namespace="SecurityExample.localhost" %>         <html>           <script language="C#" runat=server>            void Signout_Click(Object sender, EventArgs E) {              FormsAuthentication.SignOut();              Response.Redirect("login.aspx");            }            void Submit_Click(Object sender, EventArgs E) {               ReturnValues myReturnValues =               new ReturnValues();               Service1 myService = new Service1();               float myDollars =               float.Parse(USDollars.Text);               float myForeignDollars =               float.Parse(ForeignDollars.Text);               string myCountryName =               countryName.SelectedItem.Text;               myReturnValues = myService.doAllMoney              (myCountryName, myDollars, myForeignDollars);               foreign.Text =               "The foreign amount returned was"               + myReturnValues.returnAmountForeign;               us.Text = "Amount in American Dollars: "               + myReturnValues.returnAmountUs;               moneyname.Text = myReturnValues.moneyName;          }          </script>          <body>           <h3>Do Money Conversion</h3>          <form runat=server >           <h3><asp:label  runat=server/></h3>               <asp:label  runat=server/><br>               <asp:label  runat=server/><br>               <asp:Label  Runat=server/><br>          <hr>           Select a country:           <asp:ListBox id = "countryName" Runat=server>             <asp:ListItem></asp:ListItem>             <asp:ListItem>Argentina</asp:ListItem>             <asp:ListItem>Australia</asp:ListItem>             <asp:ListItem>China</asp:ListItem>             <asp:ListItem>Mexico</asp:ListItem>             <asp:ListItem>Swiss</asp:ListItem>             <asp:ListItem>UK</asp:ListItem>           </asp:ListBox>           <br>            Enter amount in US Dollars:            <asp:TextBox  Runat=server/>           <br>            Enter amount in Foreign Currency:           <asp:TextBox  Runat=server/>           <br>           <input type="submit"                  value="get money name"                  onserverclick="Submit_Click"                  runat="server"                                    NAME="Submit1"/>           <HR width=100% size=1>           <asp:button text="Signout"                       OnClick="Signout_Click"                       runat=server                                              NAME="Button1"/>           </form>          </body>         </html>

Figure 12.7 shows Default.aspx in Internet Explorer.

click to expand
Figure 12.7: Default.aspx in Internet Explorer.

Note

From both Web page examples in this section, the methods called from the Web Service look like any other methods. The developer creating these pages has no idea that this data comes from an XML file.




Cross-Platform Web Services Using C# and Java
Cross-Platform Web Services Using C# & JAVA (Charles River Media Internet & Web Design)
ISBN: 1584502622
EAN: 2147483647
Year: 2005
Pages: 128

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net