[WCF permission control] ASP. NET Roles authorization [Part II]

Source: Internet
Author: User

To give readers a comprehensive understanding of the ASP. ENT Roles-based authorization method, we will present an example. In this example, we will adopt different authentication methods, including Windows Authentication and certificate authentication (ASP. NET Membership + Roles is a common combination of methods, which will not be demonstrated here ). For the sake of simplicity, we still follow the solution structure as shown in, and still adopt declarative authorization. Therefore, the PrincipalPermissionAttribute attribute is applied to Add a service operation method to specify its authorized role Administrators.

1: public class CalculatorService: ICalculator
2 :{
3: [PrincipalPermission (SecurityAction. Demand, Role = "Administrators")]
4: public double Add (double x, double y)
5 :{
6: return x + y;
7 :}
8 :}

1. Create a database for SqlRoleProvider

The specific RoleProvider we use is SqlRoleProvider. To this end, we need to create a database first. All ASP. NET providers, such as Membership, Roles, Profile, and Site map, can be generated using the aspnet_regsql.exe tool. After you create a database, you need to insert a record in the aspnet_Applications table to indicate the application we will demonstrate. You can directly execute the following SQL script. In this school, we name the Demo Application AspRolesAuthorizationDemo.

1: insert into [aspnet_Applications]
2: ([ApplicationName]
3:, [LoweredApplicationName]
4:, [ApplicationId]
5:, [Description])
6: VALUES
7 :(
8: 'asprolesauthorizationdemo'
9:, 'asprolesauthorizationdemo'
10:, NEWID ()
11 :,''
12 :)

2. Use ASP. ENT Roles authorization for Windows Authentication

Authorization demonstrates ASP. NET Roles authorization mode when the client credential type is Windows. Therefore, we need to update the server and client configurations. Do not forget to correct the connection string based on your actual situation. The following is the server configuration.

1: <? Xml version = "1.0"?>
2: <configuration>
3: <connectionStrings>
4: <add name = "aspNetDb" connectionString = "..." providerName = "System. Data. SqlClient"/>
5: </connectionStrings>
6: <system. web>
7: <roleManager enabled = "true" defaultProvider = "sqlRoleProvider">
8: <providers>
9: <add name = "sqlRoleProvider"
10: type = "System. Web. Security. SqlRoleProvider, System. Web, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a"
11: connectionStringName = "AspNetDb" applicationName = "AspRolesAuthorizationDemo"/>
12: </providers>
13: </roleManager>
14: </system. web>
15: <system. serviceModel>
16: <services>
17: <service name = "Artech. WcfServices. Services. CalculatorService" behaviorConfiguration = "useAspNetRoles">
18: <endpoint address = "http: // 127.0.0.1/calculatorservice" binding = "ws2007HttpBinding"
19: contract = "Artech. WcfServices. Contracts. ICalculator"/>
20: </service>
21: </services>
22: <behaviors>
23: <serviceBehaviors>
24: <behavior name = "useAspNetRoles">
25: <serviceAuthorization principalPermissionMode = "UseAspNetRoles" roleProviderName = "sqlRoleProvider"/>
26: </behavior>
27: </serviceBehaviors>
28: </behaviors>
29: </system. serviceModel>
30: </configuration>

The following is the client configuration.

1: <? Xml version = "1.0"?>
2: <configuration>
3: <system. serviceModel>
4: <client>
5: <endpoint name = "calculatorService" address = "http: // 127.0.0.1/calculatorservice" binding = "ws2007HttpBinding"
6: contract = "Artech. WcfServices. Contracts. ICalculator"/>
7: </client>
8: </system. serviceModel>
9: </configuration>

Before that, we need to create two Windows accounts Foo and Bar with the Password. Since we are using ASP. NET Roles for authorization, We need to assign corresponding permissions to them through the Roles static class. To save trouble, I will write the corresponding implementation in the service host Program as shown below. In this Code, if the Administrators role does not exist, create it and assign it to the user Jinnan-PC \ Foo (Jinnan-PC is the name of my machine. For domain accounts, ).

1: if (! Roles. RoleExists ("Administrators "))
2 :{
3: Roles. CreateRole ("Administrators ");
4 :}
5: if (! Roles. IsUserInRole (@ "Jinnan-PC \ Foo", "Administrators "))
6 :{
7: Roles. AddUserToRole (@ "Jinnan-PC \ Foo", "Administrators ");
8 :}
9: using (ServiceHost host = new ServiceHost (typeof (CalculatorService )))
10 :{
11: host. Open ();
12: Console. Read ();
13 :}

Then the client calls the service twice in the name of Foo and Bar respectively. The following is the client program:

1: ChannelFactory <ICalculator> channelFactory = new ChannelFactory <ICalculator> ("calculatorService ");
2: NetworkCredential credential = channelFactory. Credentials. Windows. ClientCredential;
3: credential. UserName = "Foo ";
4: credential. Password = "Password ";
5: ICalculator calculator = channelFactory. CreateChannel ();
6: Invoke (calculator );
7:
8: channelFactory = new ChannelFactory <ICalculator> ("calculatorService ");
9: credential = channelFactory. Credentials. Windows. ClientCredential;
10: credential. UserName = "Bar ";
11: credential. Password = "Password ";
12: calculator = channelFactory. CreateChannel ();
13: Invoke (calculator );

The Invoke method is defined as follows:

1: static void Invoke (ICalculator calculator)
2 :{
3: try
4 :{
5: calculator. Add (1, 2 );
6: Console. WriteLine ("service call successful ...");
7 :}
8: catch (Exception ex)
9 :{
10: Console. WriteLine ("service call failed ...");
11 :}
12 :}

Since Foo has been assigned the Adminstrators role since the service was started, and Bar does not, only the first service call can be successful. The final execution result also confirms this point.

1: the service is successfully called...
2: service call failed...

3. Use ASP. ENT Roles for authorization under X.509 certificate authentication

Next we will demonstrate how to use ASP. ENT Roles authorization when the client uses the X.509 Certificate. To solve this problem, you need to create three topics (CN) with the following command lines: Jinnan-PC (you can specify the name of the certificate subject), Foo, and Bar. The first serves as the service certificate, and the last two sit-side client certificates. They are automatically saved to the local machine's personal certificate storage area. Then we use the certificate management unit of MMC to import the Foo and Bar certificates to the Trusted People certificate store.

1: MakeCert-n "CN = Jinnan-PC"-sr LocalMachine-ss My-pe-sky exchange
2: MakeCert-n "CN = Foo"-sr LocalMachine-ss My-pe-sky exchange
3: MakeCert-n "CN = Bar"-sr LocalMachine-ss My-pe-sky exchange

To use the X.509 certificate as the client credential, we need to modify the configurations of the server and client. In server configuration, not only ASP-based service behavior is implemented. NET Roles authorizes the corresponding settings, and also sets the service certificate (Jinnan-PC) for the service and the certificate authentication mode (PeerOrChainTrust ). The client sets the Authentication Mode of the service certificate to None. The following is the server configuration.

1: <? Xml version = "1.0"?>
2: <configuration>
3: <connectionStrings>
4: <add name = "AspNetDb" connectionString = "..." providerName = "System. Data. SqlClient"/>
5: </connectionStrings>
6: <system. web>
7: <roleManager enabled = "true" defaultProvider = "SqlRoleProvider">
8: <providers>
9: <add name = "sqlRoleProvider"
10: type = "System. Web. Security. SqlRoleProvider, System. Web, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a"
11: connectionStringName = "AspNetDb" applicationName = "AspRolesAuthorizationDemo"/>
12: </providers>
13: </roleManager>
14: </system. web>
15: <system. serviceModel>
16: <bindings>
17: <ws2007HttpBinding>
18: <binding name = "certificateCredentialBinding">
19: <security mode = "Message">
20: <message clientCredentialType = "Certificate"/>
21: </security>
22: </binding>
23: </ws2007HttpBinding>
24: </bindings>
25: <services>
26: <service name = "Artech. WcfServices. Services. CalculatorService" behaviorConfiguration = "useAspNetRoles">
27: <endpoint address = "http: // 127.0.0.1/calculatorservice" binding = "ws2007HttpBinding" bindingConfiguration = "certificateCredentialBinding"
28: contract = "Artech. WcfServices. Contracts. ICalculator"/>
29: </service>
30: </services>
31: <behaviors>
32: <serviceBehaviors>
33: <behavior name = "useAspNetRoles">
34: <serviceAuthorization principalPermissionMode = "UseAspNetRoles" roleProviderName = "sqlRoleProvider"/>
35: <serviceCredentials>
36: <serviceCertificate storeLocation = "LocalMachine" storeName = "My" x509FindType = "FindBySubjectName" findValue = "Jinnan-PC"/>
37: <clientCertificate>
38: <authentication certificateValidationMode = "PeerOrChainTrust"/>
39: </clientCertificate>
40: </serviceCredentials>
41: </behavior>
42: </serviceBehaviors>
43: </behaviors>
44: </system. serviceModel>
45: </configuration>

The following is the client configuration.

1: <? Xml version = "1.0"?>
2: <configuration>
3: <system. serviceModel>
4: <bindings>
5: <ws2007HttpBinding>
6: <binding name = "certificateCredentialBinding">
7: <security mode = "Message">
8: <message clientCredentialType = "Certificate"/>
9: </security>
10: </binding>
11: </ws2007HttpBinding>
12: </bindings>
13: <client>
14: <endpoint name = "calculatorService" behaviorConfiguration = "ignoreCertValidation"
15: address = "http: // 127.0.0.1/calculatorservice" binding = "ws2007HttpBinding" bindingConfiguration = "certificateCredentialBinding"
16: contract = "Artech. WcfServices. Contracts. ICalculator">
17: <identity>
18: <certificateReference storeLocation = "LocalMachine" storeName = "My" x509FindType = "FindBySubjectName" findValue = "Jinnan-PC"/>
19: </identity>
20: </endpoint>
21: </client>
22: <behaviors>
23: <endpointBehaviors>
24: <behavior name = "ignoreCertValidation">
25: <clientCredentials>
26: <serviceCertificate>
27: <authentication certificateValidationMode = "None"/>
28: </serviceCertificate>
29: </clientCredentials>
30: </behavior>
31: </endpointBehaviors>
32: </behaviors>
33: </system. serviceModel>
34: </configuration>

Now, what I need to do is assign Roles to the two users in the certificate through the static type Roles. As we have said before, when the client uses a certificate as the client credential, the user name must be in the format of <topic name >;< <fingerprint> ). The topic name of Foo is CN = Foo. You can use the certificate management unit of MMC to view the fingerprint of the certificate. For example, the fingerprint content is 50819320daaf1bad9de8823d3216be9b45060c4d. Then we only need to authorize the user name "CN = Foo; 50819320daaf1bad9de8823d3216be9b42460c4d. We also implement role allocation in the service host Program.

1: if (! Roles. RoleExists ("Administrators "))
2 :{
3: Roles. CreateRole ("Administrators ");
4 :}
5: if (! Roles. IsUserInRole ("CN = Foo; 50819320daaf1bad9de8823d3216be9bda-60c4d", "Administrators "))
6 :{
7: Roles. AddUserToRole ("CN = Foo; 50819320daaf1bad9de8823d3216be9bda-60c4d", "Administrators ");
8 :}
9: using (ServiceHost host = new ServiceHost (typeof (CalculatorService )))
10 :{
11: host. Open ();
12: Console. Read ();
13 :}

Then the client uses two different certificates for Foo and Bar as the credential for service calling. The corresponding client program is as follows. Depending on the permissions, only the first service call can be successful.

Client Program:

1: ChannelFactory <ICalculator> channelFactory = new ChannelFactory <ICalculator> ("calculatorService ");
2: channelFactory. Credentials. ClientCertificate. SetCertificate (StoreLocation. LocalMachine, StoreName. My, X509FindType. FindBySubjectName, "Foo ");
3: ICalculator calculator = channelFactory. CreateChannel ();
4: Invoke (calculator );
5:
6: channelFactory = new ChannelFactory <ICalculator> ("calculatorService ");
7: channelFactory. Credentials. ClientCertificate. SetCertificate (StoreLocation. LocalMachine, StoreName. My, X509FindType. FindBySubjectName, "Bar ");
8: calculator = channelFactory. CreateChannel ();
9: Invoke (calculator );

Output result:

1: the service is successfully called...
2: service call failed...

From: http://www.cnblogs.com/artech/archive/2011/07/04/asproles02.html

Related Article

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.