Application of role architecture security and Web Services Enhancements 2.0

Source: Internet
Author: User
Tags xml example xml parser

Microsoft. NET Framework and Microsoft ASP. NET support security features of multiple programs. Therefore, if you only needHttpContext. Current. User. IsInRole ()A similar structure can simultaneously access the Web server by using WSE architecture. Is it great? In this article, I will show you how to integrate the features of WSE 2.0 with the. NET Framework role architecture permission system, and then upload and verify the information.

In the Web application or Web server of the unified system, you can only rely on the certificate and encryption method of IIS (SSL. In this case, you can set a destination to allow users to access the logon credential through HTTP Communication Protocol (by using HTTP basic or Windows integrated security.

At first, you may think that it is a good idea to use HTTP to verify Web Server requests. However, once WS-Routing goes out, the website will be changed accordingly: there will be no direct HTTP access between the receiver and the most recent receiver. Instead, many different route entries will be used for routing. In this way, all the security methods (such as selective additional components) of zookeeper are lost, because it cannot guarantee the integrity and security of the end-to-end information.

One of the methods to provide end-to-end services for these Web Services is to use the X.509 Certificate to post the published information based on the WS-Security Specification.

Chapter II Jie XI

You can use Verisign and other well-known Certificate Authority (CA), or use Windows Certificate Services to directly create your own CA to obtain an X.509 Certificate. After installing this service-this service is an optional component of Windows 2000 Server or Windows Server 2003-you can direct the scanner to http: // <servername>/certsrv to request a new certificate. After the system administrator approves your requirements, you can use the same Web application through http: // <servername>/certsrv adds the new certificate to your private certificate storage area. In addition, when you enter the verification code, remember to manually select the location of the storage area (including the "actual location 」), to add the root certificate of the certificate to the local computer storage area of the Web server.

After an X.509 Certificate is created and obtained, you can use it to request Web services. But do not worry about it. First, you must Enhancements 2.0 for the website. In 「. NET DeveloperIn this mode, after installing WSE 2.0, you can click the right button on any case in Visual Studio. NET and selectWSE Settings 2.0To open the speaker as shown in [Example 1.

[Constraint 1] using Web Services Enhancements 2.0

Once you select this token, some changes will occur. Microsoft. Web. Services. dll will be automatically added to the trial. Second, and more importantly, [join the Web quiz...] the line with the [update Web Quiz] command will change, so that you can access other content later. For example, you can change the security token primitive. The command line is changed to create a second Proxy for each Web Examination. The new Proxy name suffix will append the "Wse" character (for example, the Proxy will name "MyServiceWse" instead of "MyService 」), framework will select different base types for them: WSE Proxy is not the same as non-WSE ProxySystem. Web. Services. Protocols. SoapHttpClientProtocolAccept, but chargeMicrosoft. Web. Services. WebServicesClientProtocol, Including various additional features.

With this new base type, you can access WSESoapContextAnd add the WS-Security token key and signature chapter to the token. I have set up the traffic manager service to demonstrate the Security token function of the color frame architecture, as shown below:

using System;using System.Web.Services;using System.Security.Permissions;[WebService(Namespace="http://schemas.ingorammer.com/wse/role-based-security-extensions/2003-08-10")]public class DemoService: System.Web.Services.WebService{   [WebMethod]   public string HelloWorld()   {      return "Hello World";   }}

Then, I added the Web browser exam to the trial, specified its "URL Behavior" as "dynamic", and created the following app. config example to specify the server location and the license that should be used by the terminal. If you are using this example on your computer, please remember to specify the certificate name in your private certificate storage area!

<configuration>   <appSettings>      <add key="RoleBasedSecurityClient.demosvc.DemoService"       value="http://server/WSEDemo/DemoService.asmx"/> <add key="CertificateName" value="user1@example.com"/>   </appSettings></configuration>

In this way, you can use Web Services Enhancements 2.0 to create Binary Security metadata elements. The generated token will be appended with this metadata element, and it will be used to implement the Encrypted Signature Name. In the following client program examples, the features I added can be used to access the user's private certificate storage area, and they are found in the organization repository (as shown above).

Public static void Main (string [] args) {String sto = X509CertificateStore. MyStore; // open the primary certificate Storage Area X509CertificateStore store = X509CertificateStore.CurrentUserStore(sto);Store. OpenRead (); // find the certificate you want to use String certname = System.Configuration.ConfigurationSettings.AppSettings["CertificateName"]; X509CertificateCollection certcoll = store.FindCertificateBySubjectString(certname);If (certcoll. count = 0) {Console. writeLine ("Certificate not found");} else {X509Certificate cert = certcoll [0]; DemoServiceWse svc = new DemoServiceWse (); SoapContext ctx = svc. requestSoapContext; // use your certificate to post your interest SecurityToken tok = new X509SecurityToken(cert); ctx.Security.Tokens.Add(tok); ctx.Security.Elements.Add(new Signature(tok));// Call Web Service String res = svc. HelloWorld ();} Console. WriteLine ("Done"); Console. ReadLine ();}

That's the ticket! This part has already been explained, and you should have learned how to release the excellent information. If you want to learn more about the solution and its content, please refer to Matt Powell's article "use Web Services Enhancements to enter the WS-Security Certificate and data register chapter (English)" to obtain the privacy token.

Uses declarative and role-based architecture security

That's good. The warning has been completed. Next? On the one hand, you can directly[WebMethod]Access Security token primitive and its certificate, and check whether it is called the security token primitive required by the server. Although this practice seems very practical at the beginning, you must test that your application will support multiple users, each user will have his/her own license. In addition, if the structure of your Web server infrastructure is easier than the preceding examples, then, you may need users with different roles. The permissions of each role are different. Therefore, only users of a specific role can call certain methods.

You can directly access a typical HTTP architecture Web ApplicationHttpContextIn this way, the Windows user group or Active Directory group can be used to check the user information as follows:

[WebMethod] public void AuthorizeOrder (long orderID) {if (! HttpContext.Current.User.IsInRole(@"DOMAIN\Accounting")) Throw new Exception ("Only members of 'accounting' may call this method."); //... update the information}

You can also use this limit method to check the permission set for One-Step score. For example, you can use certain numeric values to calculate the score. In the following example, a user with a role of "HR" can call the method, but only a user with a role of "PointyHairedBoss" can raise the salary to a specific gold medal or above:

Public void SetMonthlySalary (long employeeID, double salary) {if (! HttpContext.Current.User.IsInRole(@"DOMAIN\HR")) Throw new Exception ("Only members of 'hr' may call this method."); if (salary> 2000) {if (! HttpContext.Current.User.IsInRole(@"DOMAIN\PointyHairedBoss")) Throw new Exception ("Only the pointy haired boss might set salaries larger than 2 K");} //... update information}

The above program uses ASP. NET function-render management this function will cause a slight flaw in our case: in reality, this function relies on HTTP verification, instead of using the end-to-end authentication configuration, we have not solved our needs. Another shortcoming is that user role members are determined to view their Windows or Active Directory group members. Therefore, if your application requires permission verification, a large number of Windows groups will be generated-this will drive your system administrators crazy.

The custom security token primitive administrator unblocks the token

Fortunately, WSE 2.0 provides the necessary charge-filling interception programs for you to implement the role architecture security on your own. However, the procedure is simple: you only need to provide the necessary information to the Runtime to determine the user's role members. After all, how else the Framework should be sent by the members of the PointyHairedBoss role.

To enable role architecture security in this environmentMicrosoft. Web. Services. Security. Tokens. X509SecurityTokenManagerDerived from the token Security token primitive administrator. Later, I will discuss this new dynamic primitive manager, which will retrieve the organizational structure (as shown below ), in order to determine the effect of the Credential and role:

<?xml version="1.0" encoding="utf-8" ?> <CertificateMapping>  <Certificates>    <!-- user1@example.com -->    <CertificateMap Hash="f5 06 ba 1d 76 3b 59 1f ac 0c 3d ff e8 52 a3 41 44 b5 ed b1">      <Roles>        <Role>PointyHairedBoss</Role>        <Role>Accounting</Role>        <Role>HR</Role>      </Roles>     </CertificateMap>    <!-- user2@example.com -->    <CertificateMap Hash="d7 fd 06 0d 43 7f 8f bb df a2 ee 9a 55 e4 c4 49 93 65 99 e4">      <Roles>        <Role>Accounting</Role>        <Role>HR</Role>      </Roles>     </CertificateMap>  </Certificates></CertificateMapping>

In this Organization, each credential that you want to assign a role must have<CertificateMap>. The certificate can be used for identification. In this example, you can use the Certificate Authority (CA) by using the Windows Certificate Services management tool, click [start]> [System Management Tools]> [license certificate permission list]. When you select this tool and obtain the original Token, you will see the token window shown in [Example 2, this allows you to copy the workbook to the clipboard.

Just open Internet Explorer and click [tools]> [Network Selection]> [content]> [certificate], you can also access the same information of all the user certificates in the current user certificate storage area.

[Copyright 2] certificate holder information

Then you can use this zookeeper to create a new<CertificateMap>Role to specify the role associated with a specific certificate. LaterXmlSerializerThis case will be retrieved, and the case will be based on two types of differences below, and the original serialization of the object will be performed:

public class CertificateMapping{   [XmlArrayItem(typeof(CertificateMap))]   public ArrayList Certificates = new ArrayList();   public CertificateMap this[String hash]   {      get      {         foreach (CertificateMap cert in Certificates)         {           if  (cert.CertificateHash.Replace(" ","").ToUpper() == hash.ToUpper())              return cert;                  }         return null;      }   }}public class CertificateMap{   [XmlAttribute("Hash")]   public String CertificateHash;   [XmlArrayItem("Role", typeof(String))]   public ArrayList Roles = new ArrayList();}
Introduce X509SecurityTokenManager

The primary primitive administrator must acceptMicrosoft. Web. Services. Security. Tokens. X509SecurityTokenManagerWhen the difference is reached in the Framework, eachX509The binary Security token base will be updated accordinglyAuthenticateToken ()The method is used to compile and then to compile[WebMethod]. Therefore, this method allows you to establish a consistentIPrincipalObject, and you can roll back to the. NET security model at most.

To implement this security token primitive administrator, you must first add the token to the required namespace:

using System;using System.Collections;using Microsoft.Web.Services.Security;using Microsoft.Web.Services;using Microsoft.Web.Services.Security.Tokens;using System.Security.Principal;using System.Threading;using System.Xml.Serialization;using System.IO;using System.Web;using System.Security.Permissions; 

Then you can overrideAuthenticateToken ()Method to access the security token primitive of the internal delivery, and append the consistentIPrincipal.

namespace RoleBasedSecurityExtension{  [SecurityPermission(SecurityAction.Demand,      Flags=SecurityPermissionFlag.UnmanagedCode)]   public class X509RoleBasedSecurityTokenManager: X509SecurityTokenManager   {    protected override void AuthenticateToken(X509SecurityToken token)    {      base.AuthenticateToken(token);      token.Principal = new CertificatePrincipal(token.Certificate);     }   }} 
Introduce Identity and Principal

The role architecture security function of. NET Framework is assigned to the internalPrincipalAndIdentityBuild an object. The Principal object contains the role authorized by the current user, and the Identity object is used to store the user's related information and the way the user obtains the permission.

You canSystem. Security. PrincipalFind the two interfaces, the content is as follows:

public interface IPrincipal {    IIdentity Identity { get; }    bool IsInRole(string role);}public interface IIdentity {    string AuthenticationType { get; }    bool IsAuthenticated { get; }    string Name { get; }}

In order to complete the role architecture security token function, I actually made the self-Signed Principal (CertificatePrincipal) And Self-Signed Identity (CertificateIdentity) To access the license used by the current user's role members and certification.

Send messages to your server and useX509CertificateWhen an object is regarded as a numeric, the program uses this type of public constructor as the security primitive administrator. The public constructor may import the role response from the XML Parser (if any), or use the keystore to have the cached version in the replica changes. Then, the selector will search for the specified Token Based on the XML token. It checks whether the role's membership information includes the related records of the specified certificate. If not, an exception will be returned-or a corresponding Identity object will be created.

To implement this Principal, you must first include the required namespace:

using System;using System.Xml.Serialization;using System.IO;using System.Security.Principal;using Microsoft.Web.Services.Security.X509;

When necessary, the public constructor retrieves the XML token and checks whether the sender's certificate has been set in certmap. config. If this parameter is not set, the public schema function creates a new one.CertificateIdentityObject, and returns the exception.

Public class CertificatePrincipal: IPrincipal {private static CertificateMapping _ map; private static DateTime _ certmapDateTime = DateTime. minValue; private CertificateMap _ certmap; private CertificateIdentity _ ident; public CertificatePrincipal (X509Certificate cert) {String file = System. web. httpContext. current. server. mapPath ("certmap. config "); // Date FileInfo f = new FileInfo (file); DateTime fileDate = f. lastWriteTime; // The iterator must be rewritten into if (fileDate> _ certmapDateTime) {XmlSerializer ser = new XmlSerializer (typeof (CertificateMapping); using (FileStream fs = new FileStream (file, fileMode. open, FileAccess. read) {_ map = (CertificateMapping) ser. deserialize (fs);} _ certmapDateTime = fileDate;} _ certmap = _ map [cert. getCertHashString ()]; if (_ certmap = null) {throw new ApplicationException ("The certificate" + cert. getCertHashString () + "has not been configured. ");} _ident = new CertificateIdentity(cert);}

Other parts of Principal will provide methods for you to access the role members set in the XML example, and provide modularity to retrieveIdentityObjects:

  public bool IsInRole(string role)  {    return _certmap.Roles.Contains(role);  }  public System.Security.Principal.IIdentity Identity  {    get    {      return _ident;    }  }}

CertificateIdentityOther includeIIdentityTemplate implementation and an out-of-the-box attention, so that you can accessX509CertificateObject.

public class CertificateIdentity: IIdentity {  private X509Certificate _x509cert;  internal CertificateIdentity(X509Certificate cert)  {    _x509cert = cert;  }  public bool IsAuthenticated  {    get    {      return true;    }  }  public string Name  {    get    {      return _x509cert.GetName();    }  }  public string AuthenticationType  {    get    {      return "X.509";    }  }  public X509Certificate Certificate  {    get     {      return _x509cert;    }  }}
Beginning

The last step to complete the required functions is to use the server application program to compile the newly created render element administrator. After installing Web Services Enhancements 2.0, you can use either of the following methods to perform the operation. You can use the WSE 2.0 setting tool that I introduced in [Example 1.

To use the WSE 2.0 setting tool in Visual Studio. NET, click the right button on the Web server case and selectWSE Settings 2.0. At this time, the corresponding speaker as shown in [Example 3] appears. You must select the two operators in the list.

[Copyright 3] handling and managing Web Server case codes with WSE and ingress

Next, you can switch to the [Security] standard, and specify the name of the primary element administrator, as shown in [snapshot 4.

[4.1.4] added the graphic primitive administrator and graphic query credential settings (click to enlarge the image ).

To add a Metadata Manager, click [add...] and fill in the information, as shown in [lifecycle 5. Please note that you must specify the format of [type OTHER] objective:

<Namespace>.<Classname>,<Assemblyname>

Therefore, the complete model in this example is named "RoleBasedSecurityExtension. X509RoleBasedSecurityTokenManager, RoleBasedSecurityExtension 」.

[Clerk 5] added a Metadata Manager.

The last step is to set the original principles on the [principles] standards, as shown in [principles 6. We will slightly introduce the content of this principle.

[Aspect 6] set the source file name (click it to enlarge the image ).

After the Security token primitive administrator, original rule, self-Signed Principal, and self-Signed Identity object are combined, you can use WS-Policy, use the role architecture security in a fully descriptive manner.

Only one line of program running

At the beginning of this article, I have demonstrated two different methods for you. NET application uses role architecture security in the program: the first method is to explicitly expose the program to check the role, and the other method is to use declarative security and. to specify the security requirements of the method.

There are two similar possibilities in Web server applications that use WSE 2.0. The main difference is that we do not use. NET authorization to assign method security requirements, but use the WS-Policy function. The reason for choosing the WS-Policy function is that it can provide a powerful example: this is an XML example, however, you can send this case to the developers who are working on the website, so that they can directly determine the requirements required for each Web service.

However, let's take a look at the role Member checks that are being performed using the program. Unfortunately, we cannot use it again.SomeContext. Current. User. IsInRole ()Because there may be more than one security primitive in the sent SOAP messages. The method I selected was to provide two programming methods. The first is to check the security content currently required, and then find the X509SecurityToken used to post the complete internal message. The second Helper Program is a small package writing method that can provideSomeContext. Current. User. IsInRole ()An easy-to-use programming interface.

public X509SecurityToken GetBodySigningToken(Security sec) {   X509SecurityToken token = null;   foreach (ISecurityElement securityElement in sec.Elements)   {     if (securityElement is Signature)     {       Signature sig = (Signature)securityElement;       if ((sig.SignatureOptions & SignatureOptions.IncludeSoapBody) != 0)       {         SecurityToken sigToken = sig.SecurityToken;         if (sigToken is X509SecurityToken)         {          token = (X509SecurityToken)sigToken;        }      }     }   }   return token; } private bool CurrentCertificatePrincipalIsInRole(String role){      X509SecurityToken tok = GetBodySigningToken(RequestSoapContext.Current.Security);  if (tok == null) return false;  if (tok.Principal == null) return false;  return tok.Principal.IsInRole(role);}

In this way, you only need a line of program failover[WebMethod]To check the role members of the sender's X.509 certificate:

[WebMethod] public void SetMonthlySalary (long employeeID, double salary) {if (! CurrentCertificatePrincipalIsInRole ("HR")) Throw new Exception ("Only members of 'hr' may call this method."); if (salary> 2000) {if (! CurrentCertificatePrincipalIsInRole("PointyHairedBoss")) Throw new Exception ("Only the pointy haired boss might set" + "salaries larger than 2 K");} //... the actual operation has been removed ...}
Are there any excellent products?

It is not mentioned at the end, that is, the original rule case is used to declare the security requirements of the specified Web server. Undoubtedly, WSE 2.0 provides the best support for all the tools available in the Web server domain before its launch! You can use the WSE Settings 2.0 Statement again, instead of using the WS-Policy to write the original statement. In this remark, switch to the [original principle] Mark again, and click [Create/create sequence]. then follow the [add original principle] to open the speaker, as shown in [Example 7.

[7] It is easier to add the original principle!

As you have seen, in this statement, if you want to use declarative security using the root donews-Policy, then, you only need to specify the service location, select the [Requires role] accessors, select role types, and enter the roles required for the access server.

These settings will enable the Framework to check all sent messages to meet the security requirements described in the original response. For example, if the internal message does not obtain the seal, or the certificate has not been assigned to the role "Accounting 」, at this time, the program will send the SOAP producer response back to the consumer, informing the consumer that the internal delivery information does not conform to the original rule. Note: If the exception "cannot check the credit limit of your certificate" appears, indicates the root certificate of your self-authority certificate in the "local computer" storage area. To secure the root certificate, go to http: // <your_certificate_server>/certsrv, in the manual import certificate, you can manually select the import location and actual import location to access the root certificate.

Summary

Through this article, you have learned how to use Web Services Enhancements 2.0 for Microsoft.. NET to establish and use the self-built security token primitive administrator, and use the token to check X.509 Certificate and apply to the role, and use the custom Principal and Identity objects to fill in the content information. You also know that in Visual Studio. NET, it is very easy to use WS-Policy to query the declarative role members and add them to the application program. In contrast to the typical HTTP architecture Security, the WS-Security Architecture method is used, so the website does not require integrity or Security according to the protocol, instead, it completely uses SOAP injection for business. In this way, end-to-end security functions can be provided through multiple endpoints and traffic controls.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.