DPS907 notes – Mon Nov 2

Introduction to security topics for your web services.


Plan for today

Here’s what we should do today:

  1. Hands-on, inspect the security components
  2. Discussion to introduce the components and some security concepts
  3. Hands-on, make improvements, and test them


Code examples for today

There are two:


  • Created by using the “Web API project v2” template
  • No customizations or additions


  • Also created by using the “Web API project v2” template
  • Adds “role” claims
  • Includes a controller that enables you to inspect and test security


Security topics for our web services, introduction

Starting point: Make sure that you understand the terms Authentication and Authorization.

Note: In documentation, abbreviations are used sometimes.

AuthN – or authN – is an abbreviation for authentication.

AuthZ – or authZ – is an abbreviation for authorization.


The following introduction was taken from a Microsoft post. It was edited to remove the parts that are not relevant to us.

From Authentication and Authorization in ASP.NET Web API, by Mike Wasson, Microsoft:

You’ve created a web API, but now you want to control access to it.

  • Authentication is knowing the identity of the user. For example, Alice logs in with her username and password, and the server uses the password to authenticate Alice.
  • Authorization is deciding whether a user is allowed to perform an action. For example, Alice has permission to get a resource but not create a resource.

[This article] gives a general overview of authentication and authorization in ASP.NET Web API.


Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.

When the host authenticates the user, it creates a principal, which is an IPrincipal object that represents the security context under which code is running. The host attaches the principal to the current thread by setting Thread.CurrentPrincipal. The principal contains an associated Identity object that contains information about the user.

If the user is authenticated, the Identity.IsAuthenticated property returns true. For anonymous requests, IsAuthenticated returns false.


Authorization happens later in the pipeline, closer to the controller. That lets you make more granular choices when you grant access to resources.

  • Authorization filters run before the controller action. If the request is not authorized, the filter returns an error response, and the action is not invoked.
  • Within a controller action, you can get the current principal from the ApiController.User property. For example, you might filter a list of resources based on the user name, returning only those resources that belong to that user.

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

You can apply the filter globally, at the controller level, or at the level of inidivual actions.


Read the article’s section titled “Using the [Authorize] Attribute” for more information.

Also, from a different Mike Wasson article (on asp.net/web-api):

In Visual Studio 2013, the Web API project template gives you three options for authentication:

  1. Individual accounts. The app uses a membership database.
  2. Organizational accounts. Users sign in with their Azure Active Directory, Office 365, or on-premise Active Directory credentials.
  3. Windows authentication. This option is intended for Intranet applications, and uses the Windows Authentication IIS module.

Individual accounts provide two ways for a user to log in, Local login, and Social login.

With Local login, the user registers at the site, entering a username and password. The app stores the password hash in the membership database. When the user logs in, the ASP.NET Identity system verifies the password.

For both local and social login, Web API uses OAuth2 to authenticate requests.

In this article, I’ll demonstrate a simple app that lets the user log in and send authenticated AJAX calls to a web API. You can download the sample code here. The readme describes how to create the sample from scratch in Visual Studio.


Transition your knowledge of web apps security

As a user of the web, you have experience with web apps that have security components.

As a web programmer, you have some experience with security-related coding tasks. In BTI320 / INT322, you designed and created a credential store, to hold usernames and passwords. In addition, you coded a login form, and the credential validation process. An access control list based scheme was used to protect resources.

In BTI420 / INT422, you used the ASP.NET Identity components to do most of the work described above. The Authorize attribute was used on controllers and methods, and you learned that the security infrastructure took care of controlling access to resources.

But in general, how does security work?

The most common scheme in web apps – and used by ASP.NET Identity – is that the credential validation process creates an HTTP cookie. The cookie holds information about the authenticated user, but does not include sensitive or secret data. After a successful login, the server delivers the cookie with the response, and the browser saves the cookie in its cookie store.

How do you know this? Login to an ASP.NET MVC web app. Then, use the browser’s developer tool or inspector to examine the cookies collection for that web app/site. You will see a cookie named “.AspNet.ApplicationCookie“. The browser will include the cookie with every subsequent request to the web app/site.

How does security work for a web service?

Well, a user does not use a browser to interact with the web service. Therefore, we cannot use an HTTP cookie. Instead, an access token is used.

Instead of using an HTML Form for login, a requestor will send a specially-formatted “login” request to a resource in the web service. The credential validation process creates an access token. Like a cookie, an access token holds information about the authenticated user, but does not include sensitive or secret data. The token is delivered as the response, to the requestor. The requestor must then take some action to save the token.

On subsequent requests to the web service, the requestor must include the token in an Authorization header. The ASP.NET Identity components implement the OAuth 2 authorization framework, so the format of the header is:

Authorization: Bearer _VL-_nDUmUydRHeeRV9LNzuN3ZGrg0Ty1V_0Jt4gWBw4... (etc.)


Hands-on inspection of a project’s security components

In this section, you will learn about a project’s security components, by creating and inspecting a project.

For best results, create a new Web API project that uses Individual User Accounts. A project that’s based on the “Web API project v2” template meets this specification.

Also, download and open the ProjectWithSecurity code example. It has been marked up with “Attention” task list tokens, so be sure to open/display the Visual Studio Task List too.

This topic is supported by a 15-minute video:


1. Configure security, and load components when the app loads

Look at the Startup class, in the App_Start/Startup.Auth.cs source code file. When the app loads, security components are loaded and configured.

Look at the WebApiConfig class, in the App_Start/WebApiConfig.cs source code file. It does two very important tasks:

  1. It assumes responsibility for the authentication task.
  2. It loads and configures the authentication component, to work with bearer tokens.


2. Locate the security-related storage components

You have noticed that all of your web service projects include an IdentityModels.cs source code file. It includes an ApplicationUser class, and a data context.

When the database is accessed for the first time, the security components cause the security-related database tables to be created.


3. Locate the security-related controller and view model components 

The Account controller has actions that enable a user to register for a new account, and other tasks.

Study the Register method.

Next, study the account binding models, for objects sent to the account controller as parameter arguments/values.

Finally, study the account view models, for objects returned by account controller actions.


4. Inspect the built-in authentication component

The ApplicationOAuthProvider class (in the Providers folder) performs authentication-related tasks.

The app’s “token endpoint” – at URI http://host.example.com/token – is mapped (by default) to the GrantResourceOwnerCredentials method.

When sending a POST request to that endpoint, the requestor must use this content type:

Content-Type: application/x-www-form-urlencoded

Three data items must be sent in the request’s entity body:

  1. grant_type=password
  2. username= (whatever user name you have)
  3. password= (whatever password…)

The data items must be formatted to match the content type, for example:



Discussion to introduce the components and some security concepts

A Web API project that uses Individual User Accounts includes the ASP.NET Identity system. If you open the NuGet Package Manager, and then search for “identity”, you will see at least three components installed. (Click to open full-size in a new tab/window.)



ASP.NET Identity adds a number of security-related components to a project.

The components can be configured.

The functionality of the components can be accessed through a number of objects that are already present in a project, and in security-related objects that are added.


Brief review of web app security topics

In your ASP.NET MVC web apps programming course, you learned how to create a project that included security components. You also used the register and login forms, and maybe some account management functions. In the project’s source code, you also learned about the built-in components.

When controlling access to resources, you learned to use the Authorize attribute.

Note: You can refresh your security topics knowledge by reviewing the professor’s class notes from the web apps programming course. Read and study the March 24 class notes. More content was in the March 26 class notes.


Accessing 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.


Preview of the next class/session

In the next class/session, we will start to go beyond a project’s “embedded” security components, to take advantage of modularity, portability, and scale.

Make sure you prepare for that class by studying the class notes and the linked and recommended readings.

Also, we will have Test 7. A reminder – there are ten (10) tests in this course. Tests 7 through 10 are scheduled for the next four (November) Thursdays (November 5, 12, 19, and 26).


Info about Lab 7

Lab 7 has been published. It is due next Monday, November 9.

It will enable you to implement some security topics and principles.

























%d bloggers like this: