HTTP security and ASP.NET Web services

xiaoxiao2021-03-06  85

Introduction

There is a topic that has been a headache that has always been a headache for web service developers, which is: How to make the IIS and ASP.NET Web services to work with security. Now we handle security issues through IIS and adjust them via ASP.NET. ASP.NET can accept identity information provided by IIS and use this information to understand who of the caller, or use code access security to perform a specific operation on a web service. For many people, the biggest problem is how to make .NET applications utilize built-in IIS security protection. In the near future, WS-Security will be your better choice. Before that day, HTTP level safety protection will be a method of many people used to ensure information security.

When performing a Web method in a secure manner, you must involve the following:

Secure the acting of the listening conversation cannot see the data directly. Integrity provides the recipient to the ability to detect the SOAP message. Authentication answers the "Who is the caller is". Question to answer the "caller if the caller has the right to access the Web method". Recognize the procedure to prevent the client from fraud or denial in transaction processing.

These security protection features are often used in conjunction. Authentication allows authorization and recognition. The confidentiality measures provided by SSL also include integrity and authentication mechanisms. This article assumes that you are more familiar with how to use SSL and IIS. If you are not familiar, check the resources at the end of this article. At the same time, it is recommended that you find the Microsoft® Windows® server where the certificate server is installed, or install the certificate server on the available Windows server. This will help understand the SSL of SSL herein.

Encrypt and sign using SSL

Whenever you need to confidentially confidently based on HTTP-based SOAP messages, you should run your service via SSL. It will hide the data in the web service through the entity through the line.

In order to use the data in this section, X.509 certificates must be installed under the root of your web server. For information on how to do this, see HOWTO: CONFIGURE SSL IN A Windows 2000 IIS 5.0 Test Environment Using Certificate Server 2.0 (Q290625) (English). Once the certificate is properly installed, you can force SSL authentication for a virtual directory or a specific file.

Steps to open the Internet Information Services Management Console

Click "Run" in the Start menu. In the Open edit box, type inetmgr. Click OK. In this way, the IIS Management Console is open.

Request SSL for a virtual directory or a specific file is to select the correct option in IIS. To select "Correct Options", browse to the virtual directory in the IIS Management Console. If you want to request SSL for all web services that can be accessed by a given virtual directory, right-click the virtual directory, click Properties, and then click the Directory Security tab.

If you only protect a particular web service, right-click the .asmx file associated with the web service, click Properties, and then click the File Security tab. No matter which step is executed, you will see a dialog with similar to Figure 1. In "Secure Communication", click Edit, open the "Secure Communication" dialog shown in Figure 2.

Figure 1: Security tab in the IIS Management Console

Figure 2: "Secure Communication" dialog

By default, "Requires Secure Channel (SSL)" checkbox is not selected, select the check box to request SSL. SSL supports 40-bit and 128-bit encryption. The more bits used in encryption, the more difficult it is to decipher and find out the original position. This is all the work you have to do for a specific .asmx file or the entire Web service. In this way, all web service clients and web services themselves will be safe as long as the Certificate of the web server is not threatened. SSL uses an X.509 certificate containing the public key, there may also be a private key. If the private key is known to the external user, communication using public key encryption may be detected by external users, thus become unsafe. Once you need SSL when you set the resource to communicate, the information transmitted between the sender and the recipient will be encrypted and signed. That is, the external user will not be able to read the contents of the message. If the external user changes the number of bytes of the message, the message recipient can detect changes.

Authentication

In order to use IIS to give you authentication, you will need to edit the web.config file associated with your web service. To make the user's identity in HTTPContext, you need to set the /configuration/system.web/authentication/@mode property to Windows. When IIS uses one of the following authentication methods, you must set the mode properties: Basic, brief, integrated Windows Authentication (NTLM / Kerberos) or X.509 certificates. The user credentials provided by any of the above-mentioned authentication must map the user in the local computer or Active Directory.

IIS and the correct web.config settings combined with use will enable the web service to discover the caller's identity. As a new advantage, the request context will assume the identity of the caller. If you want to use Windows authentication, the web.config file should look like this:

To handle authentication, review and recognition, it is critical to open Windows authentication. The purpose of this is to make your web approach run as a caller. All records, access checks, etc. are permissions based on user permissions.

In order to force IIS to provide the caller's identity, you need to tell IIS to close anonymous access. It is so simple, true. To do this, return and open inetmgr (click Start -> "Run" and type inetmgr). Browse to the desired virtual directory. Right-click on the virtual directory or .asmx file (this depends on the identity identity you need to implement all the files in the virtual directory or only for one web service), and then click Properties. Click the Directory Security tab, as shown in Figure 1. In "Anonymous Access and Verification Control", click Edit. The Authentication Method dialog box as shown in Figure 3 will open.

Figure 3: Disabling the "Authentication Method" dialog box for anonymous access

The Authentication Method dialog allows you to configure a user to access a virtual directory or file. To pass user credentials via HTTP information, you can use basic or brief authentication. Basic and brief authentication do not provide any mechanism for ensuring messaging security. The mechanism to deliver user credentials is defined by RFC 2617: HTTP Authentication: Basic and Digest Access Authentication. Basically, use an HTTP information called Authorization to pass the username and password. For basic authentication, the username / password combination is sent in a clear text. However, it is not all like this. In fact, the username and password are sent using the Base64 encoding method in the simple express formation. If you are not familiar with Base64 encoding, you can use binary data and provide this data in text. When encoding the data, the confidential / key is not used. If you choose to use basic authentication, you can only accept credentials of SSL. This protects the Web service and caller from the threat of entities that are tried to attack to capture effective credentials. You can also use brief authentication. If you choose this option, you must understand that many SOAP toolkits do not support brief authentication. Thus, the number of toolkits that can be used using a web service will be limited. If you want to know the identity of the caller, the target SOAP toolkit supports brief authentication and the content of the SOAP message is not particularly important, please use a brief authentication. Brief authentication is encrypted using a shared confidential name called Nonce to encrypt the credentials.

Basic and brief authentication use a challenge-response mechanism. Because of this, the client and receiver will send multiple requests and responses before the web method call occurs. In basic authentication, the speed of challenge and response is quite fast. In fact, if the client knows that basic authentication is required, it will provide basic credentials yet. This speed can be a threshold value in an SSL-based connection that requires authentication server certificates and establishes session keys. In the brief identification, you need to switch Non before the credentials are encrypted. Similarly, some handshake operations need to be executed before the web service code is executed.

To enable these items for web services, just select the appropriate box in the Authentication Method dialog. If you confirm that you only need to get the authenticated user, make sure to select the Anonymous Access check box. Once this step is completed, you can do the following:

Search the caller. Use the code access security to limit the method that the caller can call.

The following web services returns the current caller information:

[WebMethod]

Public string whoami () {

RETURN "is running as a user:"

Thread.currentprincipal.Identity.Name;

}

We will modify a simple console application that calls the web service. At the beginning, the client is as follows:

Static void main (string [] args) {

Localhost.sample svc = new localhost.sample ();

Try {

Console.writeLine (svc.whoami ());

} catch (exception ex) {

Console.writeline (ex.totring ());

} finally {

svc.dispose ();

}

}

If there is no security for web service / application, the main function will print the following information:

Figure 4: No safety protection, there is no identity

If you close anonymous access by dialog box in Figure 3, the client will not be able to access the Web service. Instead, the following error message will be displayed:

System.Net.Webexception: Request failed, HTTP status 401: Access is rejected. Why is this this? By default, the Web service agent does not contain any information about the calibration or the credential to pass. Because you can't verify your identity, call the Web method failed and triggered an exception. If you want to pass the correct credentials for the current user, the easiest way is to pass along the default credentials of the current user. The TRY block in the client needs to be modified to read:

svc.credentials =

System.net.credentialcache.defaultcredentials;

Console.writeLine (svc.whoami ());

It allows the agent to access the web method because it can carry the current user's credentials and provide it to the Web method when the question. Web service returns the following results:

Run as the following users: REDMOND / SSEELY

This will use basic and brief authentication simultaneously. Authentication information is valid only for a web service call. In other words, the web service code cannot call other web services and cannot use these mechanisms to play a caller. Keep in mind that if you choose Basic authentication, you should also request an SSL connection for the file to avoid the identity of the user to monitor the monitored entity. Sometimes you may need to use different users' identity to access Web services. What should I do? You can "manually" set the credentials.

Assume that there is a user name EXAMPLE on the local Web server Ssely2, which is Test $ 123. To manually set the credentials, you must create a CredentialCache. Use the CredentialCache code to populate the cache with the NetworkCredential object. When NetWorkcredential is added to the cache, the code needs to specify the URL / authentication combination type used when returning to the specified credentials. It is possible to use the identification information of multiple sites to fill in the cache and make the cache to returns the correct credentials for each site and authentication type intelligently. To set the cache to send the correct credentials for the basic authentication challenge for the basic authentication challenge from the Web Services, use the following code:

Localhost.sample svc = new localhost.sample ();

Try {

Credentialcache Credcache = New CredentialCache ();

Networkcredential Netcred =

New NetworkCredential ("EXAMPLE", "Test $ 123", "Ssely2");

Credcache.Add (New Uri (SVC.URL), "Basic", Netcred;

SVC.credentials = CREDCACHE;

Console.writeLine (svc.whoami ());

When delivered in the URL, you will find that the URL is obtained from a web service when you are in a row containing CredCache.Add, rather than being hardened or from other sources. I like to use this method to write to the Add method, because of this most expensive, but also guarantees the web service endpoint and the endpoint used by the call Add.

If you want to use the same credentials for your brief authentication, you will read the row to the credential cache to add information:

Credcache.Add (New Uri (SVC.URL), "Digest", Netcred;

Basic authentication will work on the user registered or registered in the directory. Brief authentication only accepts users registered in the Trusted Windows domain.

Another way to verify the WEB service caller is to perform mutual authentication through SSL. The sender and recipient of the SOAP message can exchange certificates and verify each other. The server will have a certificate if you have an SSL function. If a certificate is issued to the client in the same form, the client will also have a certificate. If you already have a certificate server, you need to sign yourself and then map the certificate to your user account by the dialog shown in Figure 2. For more information, see Mapping Client Certificate To User Accounts. If you do have a certificate available, you can access these certificates through the Internet Options approved by the Control Panel. The easiest way to access this applet is to pass Microsoft® Internet Explorer. If you don't have a certificate installed, you want to get one now. Simply open Internet Explorer to browse to the Windows server where the certificate server is installed. The URL you need is http: // machine_name / certificaterv. Follow the instructions on the screen to request and install the customer certificate. Next, in Internet Explorer's Tools menu, click Internet Options, click the Content tab, and then click Certificate. A dialog that is similar to Figure 5 will be displayed.

Figure 5: Certificate dialog

You need to export a certificate so that you can be verified by the web service proxy authentication. To export a certificate, click Export Open Certificate Export Wizard. In the wizard, click Next to accept all the default options, then select a file name written to the certificate. In my example, I saved the certificate to the C: /Temp/secsample.cer. Click Next, then click Finish. Now we need to associate the certificate with a particular user.

Repeat the steps required to request SSL to ensure the security of one or all of the web services. (See Using the SSL encryption and signature section, this section starts from opening the IIS management console.) Select the Enable Certificate Mapping check box and click Edit. On the "One-to-One Map" tab, click Add. Select C: /TEMP/SecSample.Cer in the Map to Account dialog box, set the following:

"Map Name": HTTP Sample Map "Account": Select a user account. In my example, I chose Ssely2 / Example. "Password": Map to the account password. In my example, I entered Test $ 123. If the certificate identity does not match the identity associated with the certificate, it doesn't matter. When the certificate matches the certificate to the identity, the server looks for another certificate that is fully matched with the received certificate in the storage area. Why is this this? Individuals may also have a customer certificate issued by a public certificate authority. When using SSL Customer authentication, the server can map a certificate to an identity identifier in the host without the need to associate with the certificate issuer. Click to confirm your password, then click "OK" to close the dialog.

Now you need to set additional options in IIS. First, you need to clear all available authentication methods to ensure protected resources (.asmx files or virtual directories) have the permissions setup shown in Figure 6.

Figure 6: All authentication methods are cleared

Then, a customer certificate is required, as shown in Figure 7.

Figure 7: need SSL and customer certificates

Finally, you need to configure the client to load the certificate from the file and submit it to the Web service. System.security.cryptography.x509certificates.x509certificate class knows how to read X.509 certificates. To load the certificate and make it available by the web service, read the certificate and add it to the agent's customer certificate collection. Static void main (string [] args) {

Localhost.sample svc = new localhost.sample ();

Try {

X509Certificate X509 = X509Certificate.createFromcertfile (

@ "C: /TEMP/Secsample.Cer");

SVC.ClientCertificates.Add (x509);

Console.writeLine (svc.whoami ());

} catch (exception ex) {

Console.writeline (ex.totring ());

} finally {

svc.dispose ();

}

}

As expected, the output is:

Run as the following users: Ssely2 / Example

When using basic / brief authentication or X.509 to verify user identity, you can use Access Control List (ACL) to determine those users to access the directory. The method of viewing the ACL of the file or directory is to use the Windows Explorer. Right click on the file and click Properties. In the Security tab, you can add or delete users and user groups, or manage the permissions of these users operating files.

You are not at all times to add users from Web services to Active Directory. Instead, save this information elsewhere may be more preferable. To resolve this issue, the following two methods are usually used: the first method is often used for a secure Web site, which is to issue a username and password to each user, and then pass these credentials through the SOAP information head and other mechanisms. Cold Storage Example (English) uses custom SOAP information headers and HTTP modules to provide authentication. Another way is to create a custom login web service. Here, the caller is logged in via secure channels such as SSL and receives a token to use when calling other methods on the Web service. This method has been used in Favorites Web Services (English).

Use code access security

To date, we only discussed the only way to identify users. Once we know who the user is, we can use this information to authorize the user to access one or more methods within the web service. Sample users are members of the Ssely2 / SampleGroup group. If I want to limit access to the WhoAmi Web method to this group member range, you can apply the System.Security.Permissions.PrincipalPerMissionAttribute properties. Specifically, I will use the following code:

[WebMethod]

[PrincipalPermissionatTribute (SecurityAction.Demand,

Authenticated = True,

Name = @ "ssely2 / example",

Role = @ "Ssely2 / SampleGroup"]]

Public string whoami () {

RETURN "As the following users:"

Thread.currentprincipal.Identity.Name;

}

The above code is a bit extreme. It requires the name of the caller, requiring the caller to belong to the Ssely2 / SampleGroup group and the name of the caller is Ssely2 / Example. More common situations are required to belong to a particular group. This technique provides a simple way to give or reject access to a particular Web method. Using code access security - When protecting .asmx level access, it is not enough to use access control lists. Interoperability

If I didn't mention interoperability in the previous discussion on the security mechanism, I may be negligent. If you want to use a non-Microsoft Toolkit to access your web service, the most interoperable and well-tested security mechanism is to identify the calorie and SSL identification channels using basic authentication. When using this mechanism with integrated Windows authentication, you need to add usernames and passwords to the web server user or the corresponding Windows domain controller. The reason is very simple: Many web service stacks do not include understand how to handle the brief authentication HTTP part. In many cases, SSL / SOAP combinations may not support send client X.509 certificates.

summary

You can use the features in IIS and ASP.NET to ensure the security of the web service. ASP.NET Web services use a credential cache to respond to various types of authentication requests. Basic / brief authentication and SSL have the same disadvantage:

They are required to exchange messages between SOAP messages and recipients before safely send messages. This handshake mechanism limits the speed of SOAP messaging. Increasing the speed is one of the motives of the WS-Security specification (English). WS-Security abandoned transmission protocol technology based on the message-centric security model. HTTP-based security mechanisms are the best way to ensure the security of Web services before WS-Security is widely understood and deployed.

转载请注明原文地址:https://www.9cbs.com/read-95239.html

New Post(0)