Windows Azure AppFabric Introductory Teaching series (V): A preliminary study of access control Service

Source: Internet
Author: User
Keywords Nbsp; token as follows
Tags .net access access control class class program click client code

This article is the fifth article in the introductory teaching of Windows Azure AppFabric. This article provides a preliminary explanation of access control Service (ACS) in AppFabric. For subsequent learning to proceed smoothly make sure that you have browsed through the first article of this tutorial, and that you have completed the creation of the AppFabric project and namespace in this article. We know that APPFABIRC is made up of service bus and Access Control service, and we've covered service bus in the previous tutorial, so this article will briefly explain how to use ACS services to ensure security. Also, because the SWT and OAuth protocols are used in this article, readers can browse through the fourth article in this tutorial to get a quick understanding of the protocol.

Preconditions

For the following tutorials to work smoothly, make sure that the software or components below are installed:

· Microsoft. NET Framework 3.5 SP1

· Microsoft Visual Studio 2008 SP1 (or adjective)

· AppFabric SDK

· Windows Azure Platform Training kit-december Update (sample code)

Please make sure you have some WCF programming experience, if not, please browse here for a quick preliminary understanding of WCF.

Finally, make sure that you have created a AppFabric project and a service namespace. Please refer to here.

Principle:

Let's start with the general application scenario for ACS:

Client request (1) and obtain (2) an SWT token. The client then uses the SWT to invoke the service (3), which, once successfully validated by Acsauthorizationmanager, (4), can access the desired service method.

Code:

After understanding the principles of communication, let's look at how the specific code is written.

1. Under Windows Azure Platform training kit-december Update (sample code) installation directory, labs\introappfabricaccesscontrol\source\ Ex01-usingacwithsymmetrickey\begin directory, open the SymmetricKey.sln project.

The project is working properly, and we will modify the code on its basis to integrate it with ACS. First we debug and look at the operation without ACS.

Right-click the service project, Debug->start new instance, and start a service instance.

Start a client instance in the same way, and the end result is as follows.

Opening the Program.cs of the service project, we see that the program code simply mounts the Iweatherforecast service onto the http://localhost/weatherforecast.

The client project simply accesses the required service through the URI. The following figure.

Note: We see from the end that Get3daysforecast and Get10daysforecast methods can be accessed.

2. Modify the service to accept and verify the AppFabric AC token.

The SWT token must be checked when the code calls the requested content that is being inspected. Once you verify that SWT exists, you must check that it is signed with a valid key. In this case, we provide the ServiceAuthorizationManager class to implement the validation logic.

2.1 Right-click Service Item, add->existing item, enter Source\ex01-usingacwithsymmetrickey\assets, Add ACSAuthorizationManager.cs and TokenValidator.cs

2.2 Add the following bold code to the service project Program.cs:

C #

public class Program

{

Private Const String Servicenamespace = "{Insert service namespace here}";

Private Const String Tokenpolicykey = "{Insert token policy key

here} ";

Private Const string audience = "Http://localhost/weatherforecast";

Private Const string requiredclaimtype = "action";

Private Const string issuername = "https://{0}.accesscontrol.windows.net/";

public static void Main (string] args)

Change Servicenamespace to the service namespace you created in the first article of this tutorial.

2.3 Add the following bold code to the main function so that the ACS validation process is implanted into the process of the program invocation service. Once our custom ServiceAuthorizationManager class is inserted into the WCF pipeline (pipeline), it is automatically executed each time the service is invoked.

Host. AddServiceEndpoint (typeof (Iweatherforecast), binding, New Uri ("Http://localhost/weatherforecast"));

Host. Authorization.serviceauthorizationmanager = new Acsauthorizationmanager (

String. Format (Issuername, Servicenamespace),

Audience,

Convert.frombase64string (Tokenpolicykey),

Requiredclaimtype);

Host. Open ()

3. Configure clients to access the service using AppFabric access control

3.1 In the client project, Program.cs, add the following bold code:

Namespace Client

{

Using System;

Using System.Collections.Specialized;

Using System.Linq;

Using System.Net;

Using System.ServiceModel;

Using System.ServiceModel.Security;

Using System.ServiceModel.Web;

Using System.Text;

Using System.Web;

Using System.IO;

public class Program

And the following bold code:

public class Program

{

Private Const String Servicenamespace = "{Insert service namespace here}";

Private Const string issuername = "Weatherforecastclient";

Private Const String Issuerkey = "{Insert issuer key here}";

Private Const string acshostname = "Accesscontrol.windows.net";

public static void Main (string] args)

{

3.2 Add the following methods to the program class:

...

private static string Getacstoken ()

{

Request a token from AppFabric AC

WebClient client = new WebClient ();

Client. baseaddress = string. Format ("https://{0}.{ 1} ", Servicenamespace, Acshostname);

NameValueCollection values = new NameValueCollection ();

Values. ADD ("Wrap_name", issuername);

Values. ADD ("Wrap_password", Issuerkey);

Values. ADD ("Wrap_scope", "http://localhost/weatherforecast");

BYTE] responsebytes = client. UploadValues ("WRAPv0.9", "POST", values);

String response = Encoding.UTF8.GetString (responsebytes);

return response

. Split (' & ')

. Single (value => value. StartsWith ("wrap_access_token=", StringComparison.OrdinalIgnoreCase)

. Split (' = ') [1];

}

}

}

3.3 Add the following code at the beginning of the main function:

String Acstoken;

Try

{

Acstoken = Getacstoken ();

}

catch (WebException ex)

{

Console.foregroundcolor = consolecolor.red;

if (ex. Response!= null)

{

Stream exception = ex. Response.getresponsestream ();

StreamReader reader = new StreamReader (exception);

Console.WriteLine Reader. ReadToEnd ());

}

Else

{

Console.WriteLine (ex. message);

}

Console.ReadLine ();

Return;

}

Also add the following code to the corresponding position in the main function:

using (new OperationContextScope (proxy as IContextChannel))

{

String authheadervalue = String. Format ("WRAP access_token=\" {0}\ "", Httputility.urldecode (Acstoken));

WEBOPERATIONCONTEXT.CURRENT.OUTGOINGREQUEST.HEADERS.ADD ("Authorization", authheadervalue);

Call the service and get a response

4. Configure the AppFabric ACS namespace to implement access logic for a particular caller.

4.1 Click "Start"-> "Run", input cmd, enter. Switch current work path to Windowsazureplatformkit\labs\introappfabricaccesscontrol\source\assets

4.2 Create Tokenpolicy, enter the following code and execute: (Note: The following all the yellow box contents need to replace the reader's own information, service refers to the service Namespace,mgmtkey refers to management key)

ACM Create Tokenpolicy-name:weatherforecast-timeout:28800-autogeneratekey-service:{your Service Namespace}-host: Accesscontrol.windows.net-mgmtkey:{your Management Key}

Returns tikenpolicy ID = Tp_18d47a547b0f40648fdabfe753885dd4

4.3 Create scope, enter the following code and execute: (Tokenpolicyid tikenpolicy ID returned for step)

ACM Create scope-name:weatherforecast-tokenpolicyid:tp_18d47a547b0f40648fdabfe753885dd4-appliesto:http:// Localhost/weatherforecast-service:{your Service Namespace}-host:accesscontrol.windows.net-mgmtkey:{your Management Key}

Returns the scope ID = Scp_3c9c465f2be54bed809080f210914f70dab58dee

4.4 Create issuer, enter the following code and execute:

ACM Create Issuer-name:weatherforecastclient-issuername:weatherforecastclient-autogeneratekey-algorithm: Symmetric256bitkey-service:{your Service Namespace}-host:accesscontrol.windows.net-mgmtkey:{your management key}

Returns issuer ID = Iss_8c389a6764e8a26bf5133a7ab9c830f8bea33a82

4.5 Create rule, enter the following code and execute: (ScopeID for step 4.3 Returns the scope Id,inclaimissuerid is the issuer ID returned by the step)

ACM Create Rule-name:client3days-scopeid:scp_3c9c465f2be54bed809080f210914f70dab58dee-inclaimissuerid:iss_ 8c389a6764e8a26bf5133a7ab9c830f8bea33a82-inclaimtype:issuer-inclaimvalue:weatherforecastclient-outclaimtype: Action-outclaimvalue:get3daysforecast-service:{your Service Namespace}-host:accesscontrol.windows.net-mgmtkey:{ Your Management Key}

(Here we see open access to the Get3daysforecast service)

return rule ID = rul_462d5abd1326c40993f9ec2e766c0ab3b69c11093404db2736d81f5e6018caf141d2e4cdd2164335

4.6 Enter the following code and execute it to get Tokenpolicykey

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.