DPS907 WSA500 Lab 7

Security for your own web services apps. Hosted on Azure.

Read/skim all of this document before you begin work.

 

DPS907 WSA500 Lab 7 – Due Mon Nov 9

Due date: Monday, November 9, 2015, at 8:00am ET

Grade value: 8% of your final course grade

If you wish to submit the lab before the due date and time, you can do that.

Yes, your project can earn part marks if a feature is missing. 

 

Objective(s)

Configure a web service app to use security.

Use a pre-configured Identity Server that also includes an authentication service.

 

Introduction to the problem to be solved

We need a web service that can be secured. Users will be able to access resources that match their security claims.

The web service will trust an Identity Server, which will perform identity management tasks, and authentication. A user of the web service must obtain an access token from the Identity Server before they can access secured resources. The web service performs authorization, and because it trusts an access token that’s generated by the Identity Server, it is able to do this task.

The security infrastructure, known as ASP.NET Identity, is based on the OAuth 2 authorization framework.

Your work will be hosted publicly on Microsoft Azure Services.

 

Specifications and work plan

The following specifications apply to all of your work:

  • Follows best practices
  • Implements the recommended system design guidance
  • Uses Entity Framework and Code First technology
  • Deployed to Microsoft Azure Services

Ensure that there are at least four entity objects – musical instruments – in your Azure-hosted data store. You need at least that many to be sure that your app’s logic works correctly.

For this assignment, here’s what we’re looking for:

  • Use a pre-configured Identity Server
  • Create a web service that works with the Identity Server
  • Enable a user to work with their own resources, but not those of others

The in-class grading will look at your Fiddler requests that obtain and then use an access token. In other words, it will focus on the use of the Identity Server.

DPS907 students must modify the way that a user’s resources are accessed.

 

Getting started

On My.Seneca/Blackboard, in the Assignments area, there are two zip file assets.

IdentityServerV1 is the pre-configured Identity Server, created by your professor. It is “version 1”. (Another version is planned for the near future.)

Lab7Base is a working solution for your recently-completed Lab 6, created by your professor. You can use it as a base for your Lab 7 work, if you wish.

Download these files, and prepare them for use. You will use two instances of Visual Studio.

 

Identity Server work

The Identity Server (IS) has been pre-configured to work with one or more web apps or web services that you may create in the future.

When you run the app on your computer (or on a College computer-lab computer), you can login with these credentials:

User name: admin@example.com
Password: Password123!

Then, if you follow the “Admin Tasks” link (at the top), you can show the list of users that are included with the pre-configured app. You can register more users through the user interface, if you wish.

While the IS app works correctly, it is not ideal for production use. If you study the account registration workflow, you will see that its handling of claims is not adequate. (Why?) Also, it needs more account management functionality, to enable administrator users to add, change, and remove user accounts. In the future, we can make improvements, but they are not required for this Lab 7.

Run the app. Then, use Fiddler to test the app. Create some new accounts:

Target URI: /api/account/register
Method: POST
Content type: Can be either application/json, or application/x-www-form-urlencoded
Entity body if JSON: {"Email":"whatever","Password":"whatever","ConfirmPassword":"whatever"}

 

Remember the ASP.NET Identity password rules configuration. A password must:

  • Be 8 or more characters in length
  • Include a mix of upper and lower case alpha characters
  • Include one or more numeric digits
  • Include one or more symbols (e.g. @ # % etc.)

 

Then, request some access tokens:

Target URI: /token
Method: POST
Content type: application/x-www-form-urlencoded
Entity body: grant_type=password&username=whatever&password=whatever

Finally, attempt to use an access token. Make a request to the “account info” endpoint:

Target URI: /api/account/userinfo
Method: GET
Content type: application/json
Authorization header: "Bearer", a space, and then the token text

After you have completed this task, ask your professor to check your results.

 

Web service that will use security features

As noted above, you can use the Lab7Base zip file. Alternatively, you can use your own Lab 6 solution, or create a new one that implements the Lab 6 specifications.

 

Design model class

Add a property to the Instrument class, to hold the user name of the resource owner. It will be a required string value.

We need this data item, so that we can write code to enforce our resource access rule.

 

Code First Migrations configuration

After editing the Instrument design model class, and running the app, you will be told that you must enable Code First Migrations.

Do that. You need to do it anyway to prepare for Azure deployment.

If you need a reminder about the three-command sequence, review the October 1 class notes.

 

Instrument controller work

All methods in the Instrument controller will require authorization.

If you wish to deliver user information with your query or command results, then you will need to modify one or more resource models, or alternatively, you can create another resource model that inherits from, for example, InstrumentBase. That’s up to you.

 

Reminder – how to access user data at runtime

Most students will recall this topic from their ASP.NET web apps course.

After a successful authentication, the authentication process (on the server) will create a data package and return it in the response. The data package includes information about the authenticated user, but it does not include sensitive or secret data. It definitely includes the user name, and the user’s claims.

If the authentication was initiated by using a browser and a web app, the data package that’s returned is an HTTP cookie.

Alternatively, if the authentication was initiated by using an HTTP client (e.g. Fiddler), the data package that’s returned is an access token.

On subsequent requests, the data package – cookie or token – is sent with the request. In a web app, the browser handles this task automatically. When you are using Fiddler (or programming an HTTP client on, for example, an iPhone app), you must do this task.

When a web service receives a request with a token, the security infrastructure validates the token. If valid, it creates an IPrincipal object, and attaches it to the request. That way, information about the authenticated user is available to your code, as the request makes its way through the request-processing pipeline.

In your code, how do you get access to the authenticated user information? The User property.

In a controller, it’s simply the top-level User property. Also, if you want to determine whether a request is authenticated, the Request.IsAuthenticated property will tell you.

In a repository (or manager) service layer module, it’s the HttpContext.Current.User property. Also, if you want to determine whether a request is authenticated, the HttpContext.Current.Request.IsAuthenticated property will tell you.

 

Repository work

In the specification above:
Enable a user to work with their own resources, but not those of others

A good way to surface information about the authenticated user is to add a property to your base Repository<T> class.

// Security context for the currently-executing request
protected ClaimsPrincipal User =
    HttpContext.Current.User as ClaimsPrincipal;

 

Then, each entity-specific repository can directly work with the User property. Use the code editor to inspect the User property. Look for the user name, and other useful members.

Note:

We cast it to ClaimsPrincipal (“as ClaimsPrincipal”), because that type is the best for our purposes.

 

All entity-specific repository methods need to be modified:

GetAll must fetch only the resources that match the user name of the requestor.

As above, GetById must fetch the resource only if it matches the user name of the requestor.

Add must set/configure the user name of the requestor when it is added and saved.

SetPhoto and SetSoundClip must do the work only if it matches the user name of the requestor.

 

Security infrastructure

As you know, the web service includes the components that manage identities, and perform authentication. However, we do NOT want to use these components. Instead, we will use the separate Identity Server for those tasks.

Therefore, the security infrastructure must be modified to match this requirement. The security infrastructure is configurable, with many features and capabilities. We can custom-configure it to exactly match our needs.

In the root of your project, there is a Startup.cs source code file, which contains a partial class named Startup.

Replace the existing Configuration method with the following code:

public void Configuration(IAppBuilder app)
{
    // The following method is described in MSDN:
    // https://msdn.microsoft.com/en-us/library/owin.oauthbearerauthenticationextensions.useoauthbearerauthentication(v=vs.113).aspx
    // Adds Bearer token processing to an OWIN application pipeline.
    // This middleware understands appropriately formatted and secured tokens
    // which appear in the request header. The claims within the bearer token
    // are added to the current request's IPrincipal User.
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { });
}

The change looks deceptively simple. It is, but it has a beneficial effect. Make sure that you have read and understood the comments. (If not, ask.)

In summary, the app, using this configuration, will trust the token that was generated by the separate Identity Server.

 

DPS907 (BSD) students will modify resource access

As noted above, BSD students must modify the way that a user’s resources are accessed.

The “get all” should continue to work the same – “get all” resources for a user/requestor.

Add a new controller action (and repository method), which can “get” all resources, from all users.

Modify the “get one” controller action so that any authenticated user can fetch the resource.

 

Deploy your work to Microsoft Azure Services

Having problems deploying to or running on Azure? Check this document.

There are a few tasks that must be done before your Azure-posted work will run correctly.

 

Custom machineKey value

Recently, you learned that apps that are separated from an Identity Server will need a special configuration, so that they are using the same “machineKey” value for encryption and decryption of tokens and cookies. This topic was introduced in the November 5 class notes.

At this point in time, use that information to 1) generate a custom “machineKey”, and 2) add it to BOTH apps (Identity Server and Instruments/Lab 7).

 

Azure web app and database preparation for your Identity Server app

It appears that our Azure Pass limits us to ten (10) web apps, and two (2) database servers. Therefore, we suggest that you remove (delete) the existing web apps and databases in your account.

Notes about databases and database servers:

On the Azure Management Portal, when you view the list of databases, you will see a list that looks like the following:

list-of-databases

Although our Azure Pass limits us to two (2) database servers, that’s not a limitation for us. Why? A database server can hold multiple databases.

Therefore, when you create a new database, we suggest that you almost always choose to create it inside an existing database server.

Next, create a web app, with a database, for your Identity Server app. The suggested name is (substitute your Seneca account name for the “astudent” placeholder below):

astudent-ws2015-is.azurewebsites.net

You can now deploy your Identity Server app to this endpoint.

 

Azure web app and database preparation for your Lab 7 app

Now, create a web app, with a database, for your Lab 7 app. The suggested name is (substitute your Seneca account name for the “astudent” placeholder below):

astudent-ws2015-lab7.azurewebsites.net

You can now deploy your Lab 7 app to this endpoint.

 

Testing your work

Use Fiddler.

Ensure that it has been configured to save the message bodies in requests and responses. (A default installation does not do this.) If you are using a College computer, this has already been configured. If you installed Fiddler on your own computer, follow the instructions on this document.

Test all scenarios (use cases), using your Azure-hosted web site, if possible.

 

Saving – ‘exporting’ – your tests

On the left side list of requests, you can delete items that you don’t want included in the export.

When you’re ready to save, choose File > Export Sessions > All Sessions…

The export format will be “HTTPArchive v1.2″. Click the Next button to choose a save location (your project’s root, in the same folder as the “packages” and “lab7” folder) and specify a filename. Name the file by using the project name (e.g. “lab7.har”).

(You can test whether the export was successful. How? First, close then re-open Fiddler. Choose File > Import Sessions. Select “HTTPArchive” as the import format. Navigate to the folder that holds “lab7.har”, and select it. Finally, browse through the request-response sessions.)

 

Reminder about academic honesty

You must comply with the College’s academic honesty policy. Although you may interact and collaborate with others, you must submit your own work.

 

Submitting your work

Submit only your Lab 7 work. Do not submit the Identity Server.

At this point in time, you are familiar with the submission process:

  1. Copy your project
  2. Remove its packages, bin, and obj folders
  3. Zip and upload to the designated location on My.Seneca/Blackboard, before the due date

If you need more details, look at the info in assignments 1 through 4.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

%d bloggers like this: