App’s Security Terminologies

Basic terminologies when dealing with OAuth security in the context of app (web application, api, mobile application, etc).

Authentication
The process of proving you are who you say you are.

Authorization
The act of granting an authenticated party permission to do something. It specifies what data you’re allowed to access and what you can do with that data.

Identity
Refer to users who request access to resources. Users have to proof their identity is who they said they are, usually through authentication process.

Flow (aka. grant type)
Methods through which applications can gain Access Tokens and by which you grant limited access to your resources to another entity without exposing credentials.

Token
A piece of data contain information about users and apps. Common types of tokens:

  1. Id token
  2. A token used to identify user.

  3. Access token
  4. A token used to access some kind of resources, ie: api.

  5. Refresh token
  6. A token used to refresh access token.

Hash
Function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called hash values, hash codes, digests, or simply hashes.

Encrypt
Convert (information or data) into a cipher or code, especially to prevent unauthorized access. Common methods of encryption:

  1. Asymmetric
  2. A form of encryption where keys come in pairs. Public keys which may be disseminated widely, and private keys which are known only to the owner. Public keys are used to encrypt and private keys are used to decrypt.

  3. Symmetric
  4. A form of encryption which only use one key (as opposed to pair of keys in Asymmetric). The key is used to encrypt and decrypt.

Decrypt
Make a coded or unclear message able to be understood.

Public private key
See asymmetric encryption above.

Federation
The linking a users’ electronic identity and attributes, stored across multiple distinct identity management systems.

References:
Microsoft
Auth0
Wikipedia

Another Reading List

Cross Tab Communication with Javascript

This post lays out an interesting problem, how can Javascript communicates across browser tab (or iframe or window)? There are few different approaches with pro and cons of each.


Use read-only replicas to load-balance read-only query workloads

With new vCore pricing model, Azure offers SQL solution with better features. One of those is no-cost, built-in read-only scale out database. Read more on the details here.


Overview of Microsoft Authentication Library (MSAL)

MSAL is the new library to authenticate with Microsoft Identity Platform (or what it used to be Azure AD endpoint). It’s replacing ADAL (which only used to authenticate to Azure AD endpoint – v1). The new version support authentication beyond Azure AD which includes personal account (hotmail.com / outlook.com) and social accounts like Facebook / Twitter, etc.  For more details on Microsoft Identity Platform: https://docs.microsoft.com/en-us/azure/active-directory/develop/about-microsoft-identity-platform


Authentication flows

There are many authentication flows in the world of authentication. This Microsoft documentation gives overview of each auth flow and how it’s being used. Primarily for Microsoft Identity Platform, but generally applicable to other platform / framework as well.  The more details coverage of each auth flow can also be found here: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow


Google Spent 2 Years Studying 180 Teams. The Most Successful Ones Shared These 5 Traits

Great achievement can sometime be done by one person. But most of the time, it’s a team. This post talks about Google research into what makes the most successful one. It’s along the same line of previous studies around motivation, more psychological than anything else.


Web API .Net with Basic Authentication

Github project.

Notes:
1. This work on .Net framework 4.6.1.
2. Authorization part is not covered.

The core authentication code is in `Security/BasicAuthAttribute.cs`. This class inherit from following:

ActionFilterAttribute
So we can use it as attribute to decorate controllers or actions.

IAuthenticationFilter
To invoke WebApi’s authentication pipeline. Some developer like to use `IActionFilter` for authentication, while it may work, it is not a best practice as `IActionFilter` execute later in the WebApi stack.

IAuthenticationFilter implement 2 methods:
1. `AuthenticateAsync`. Run first. This is code to authentication user. Caller pass in credential in request header. First we begin by parsing the header and user name/password credential caller passed in. Then authenticate user, in Github project, I add user to generic principal but in production app, you should validate credential against security provider (ie: ADFS, Auth0), etc.
2. `ChallengeAsync`. Run after `AuthenticateAsync`. This is where authentication failed and we can challenge caller to prove them selves, which is done by passing `Authorization Basic` in response header.

Usage
There are 3 ways to use this attribute in WebApi.
1. Globally. Every actions will require authentication.

WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    // Add global authentication
    config.Filters.Add(new BasicAuthAttribute());

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

2. In entire controller. Every actions under that controller will require authentication. Notice the `[BasicAuth]` decoration.

ValuesController.cs

[BasicAuth]
public class ValuesController : ApiController
{
    public IEnumerable Get()
    {
        return new string[] { "value1", "value2" };
    }
            
    public string Get(int id)
    {
        return "value";
    }
}

3. In specific action. Notice the `[BasicAuth]` decoration.

ValuesController.cs

public class ValuesController : ApiController
{
    public IEnumerable Get()
    {
        return new string[] { "value1", "value2" };
    }

    [BasicAuth]
    public string Get(int id)
    {
        return "value";
    }
}

Barebone Angular Project with Auth0

Simple project to demonstrate how to use Auth0 in Angular project, download code on Github.

To get started, you must have Auth0 account.
To setup the project, update following value in `environment.ts`:
1. Client ID. This is the id of your app you created in Auth0 dashboard. See here.
2. Client Domain. Your Auth0 domain to authenticate user. See here.
3. Callback Url. This is url Auth0 will redirect to after user is authenticated. This url must be white-listed in Auth0 dashboard. See here.
4. Logout Url. This is url Auth0 will redirect to after user logout. This url must be white-listed in Auth0 dashboard. See here.

The juice is on `service/auth.service.ts`, following are explanations of each methods:
1. Login
Call Auth0 authorize method to authenticate users. The method will redirect user to Auth0, if user is not authenticated, a login screen will displated, if user is authenticated Auth0 will redirect to callback endpoint and pass id token.

2. HandleAuthentication
Parse response object from Auth0 which contain id token, access token, expiration time and other information. Redirect user to appropriate url depend on the authorization results.

3. SetSession
Set authentication tokens and expiration in browser’s storage. User is authenticated.

4. Logout
Remove authentication tokens and expiration from browser’s storage. User is not authenticated anymore.

5. IsAuthenticated
Check browser’s storage to see if user is authenticated.

Adding ASP.Net Identity (with OWIN) to Existing MVC 5 Project

The simple way is start empty MVC project with authentication and pick and choose ASP.Net Identity part you want to implement.

Here is the summary:

  • Install dependencies. See https://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity, scroll down to “Components of ASP.Net Identity”
    • Entity Framework
    • OWIN
    • Microsoft.AspNet.Identity.Core
    • Microsoft.AspNet.Identity.EntityFramework
    • Microsoft.AspNet.Identity.Owin
    • Microsoft.Owin
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security
    • Microsoft.Owin.Security.Cookies
    • Microsoft.Owin.Security.OAuth
    • Microsoft.Owin.Security.Google (if you want allow external login with Google)
    • Microsoft.Owin.Security.Facebook (if you want allow external login with Facebook)
    • Microsoft.Owin.Security.Twitter (if you want allow external login with Twitter)
    • Netwonsoft.Json
  • In Web.config
    • Under
      <system.web>

      Add

      <authentication mode="None" />

      This is to remove IIS authentication, because we are going to use OWIN

    • Add all OWIN dependencies
  • Add Startup.cs. This is a startup class run by OWIN
    • Don’t forget its dependency, Startup.Auth.cs in App_Start folder
  • Add all classes in IdentityConfig.cs
    • There are 4 classes, EmailService, SmsService, ApplicationUserManager, ApplicationSignInManager. I’d like to separate them into different files
  • Add all classes in IdentityModels.cs
    • There are 2 classes, ApplicationUser, ApplicationDbContext. I’d like to separate them into different files

Those are the basic setup needed for ASP.Net Identity. The rest of the setup is front-end side, AccountController and ManageController, which has its own view models and CSHTML.

OAuth2 Flows

Cliff notes from Dominick Baier’s OAuth2 Flows.

Authorization Code Flow

oauth2-flows-1

Characters: web application (server-based) clients, confidential and secured client where nobody can see user credential, human involves, consent screen, authorization happens in authorization server.

Apply to: web applications

Steps:

  1. Request authorization.
  2. Request token.
  3. Access resource.

Implicit Flow

oauth2-flows-2

Characters: native / local clients, user-agent based clients, human involves, consent screen, authorization happens in authorization servers.

Apply to: third party native applications (JavaScript application is included).

Steps:

  1. Request authorization & token.
  2. Access resource.

Resource Owner Credential Flow

oauth2-flows-3

Characters: trusted clients, no human involvement, no consent screen, authorization happens in client.

Apply to: official native applications (JavaScript application included).

Steps:

  1. Request token with resource owner credentials.
  2. Access resource.

Client Credential Flow

oauth2-flows-4

Characters: client to Service communication, no human involvement, no consent screen, authorization happens in client.

Apply to: machine to machine communication, service communication to authorization server without act as.

Steps:

  1. Request token with client credentials.
  2. Access resource.

Assertion Flow

oauth2-flows-5

Characters: use one of the ‘core’ flows, access another trusted system (partner).

Apply to: translate between identity management system (ADFS’s saml to ThinkTecture’s jwt), communication with partner’s resources using client’s credential.

Steps:

  1. Request token using ‘core’ flow (Authorization Code, Implicit, Resource Owner Credential, Client Credential).
  2. Request token using ‘assertion’ flow.
  3. Use token.