Authentication & Authorization

Under construction

Terms

Authentication
The process of securely identifying a user. Who is this user? Is the user really who they represent themselves to be?
Authorization
The process of determining what access, rights or permissions a user is allowed. Is this user authorized to access this resource?

They usually go together: Login with username/password (Authentication) and then access specific resources exclusive to a role, e.g. Admin, Purchaser, Supplier (Authorization) But it doesn't have to be. The concepts are orthogonal.

Authorization without Authentication

  • Use a coupon to purchase something at a discount
  • Pass a CAPTCHA to authorize as a human
  • Requiring computers on WOU's network to have Cisco Clean Access Agent installed before using the network
  • Purchasing something with Apple Pay (from the standpoint of the store)
  • Colored wristband at an amusement park for access to a ride

How to Authenticate?

  • Accept primary credentials: username and password, PIN or shared secret, one-time pad, DNA
  • Accept indirect primary proof: public key cryptography
  • Accept previously awarded token or certificate: smart card, E-ZPass, cookie
  • Accept proof from a trusted 3rd party: birth certificate, driver's license, ...

Claims-based Authentication

A claim is a statement that one subject makes about itself or another subject. The statement can be about a name, identity, key, group, privilege, or capability, for example. Claims are issued by a provider, and they are given one or more values and then packaged in security tokens that are issued by an issuer, commonly known as a security token service (STS).

From: A Guide to Claims-Based Identity and Access Control

  • "Claims-based identity allows you to factor out the authentication logic from individual applications. Instead of the application determining who the user is, it receives claims that identify the user."
  • "Claims help you to factor authentication logic out of your applications."
  • You send your users to a 3rd party to authenticate and then you trust the claim made by this trusted 3rd party
  • You don't need to store authentication credentials
  • The user doesn't have to trust YOU with their credentials

Different Kinds of Authentication and Uses

HTTP Basic Authentication

HTTP Basic Authentication popup dialog

Client-Server Exchanges

Challenge response for HTTP Basic Auth

Considerations

  • Dates back to 1997
  • Authorization header field is sent in clear text
  • Authorization header field is sent automatically to known host in the known "realm"
  • Use is limited to certain URI's on the host (realm)
    [RFC7617]
    For example, given an authenticated request to:
    
    http://example.com/docs/index.html
    
    requests to the URIs below could use the known credentials:
    
    http://example.com/docs/
    http://example.com/docs/test.doc
    http://example.com/docs/?page=1
    
    while the URIs
    
    http://example.com/other/
    https://example.com/docs/
    
    would be considered to be outside the authentication scope.
  • Simple and easy to implement/test
    $ curl --user 'uid:pass' https://mysite.com/path/to/resource
  • There is no mechanism to log off
  • It was tempting for servers to store raw UserID:Password directly
  • Vulnerable to spoofing by counterfeit servers
  • Limits on characters in UserID and Passwords (no ':' or control characters)
  • HTTPS/TLS MUST be used for all URI's in the "realm"

Why ever use it? Some REST APIs

  • Secure API endpoints with Basic Auth over HTTPS
  • No need for user to enter UserID and Password
  • Generate random (but unique and unguessable) API Key and Secret and give to end user
  • Allow user or provider to invalidate/regenerate keys
  • Can be good for automated or embedded systems with limited access to more modern authentication stacks
  • Susceptible to attacks without adding additional steps

In ASP.NET MVC?

public class BasicAuthenticationAttribute : ActionFilterAttribute
{
  public string BasicRealm { get; set; }

  public BasicAuthenticationAttribute(string realm)
  {
    this.BasicRealm = realm;
  }

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    var auth = filterContext.HttpContext.Request.Headers["Authorization"];
    if (!String.IsNullOrEmpty(auth))
    {
      var cred = System.Text.ASCIIEncoding.ASCII.GetString(
                      Convert.FromBase64String(auth.Substring(6))).Split(':');
      var user = new { Name = cred[0], Pass = cred[1] };
      //if (user.Name == Username && user.Pass == Password && ) return;
    }
    filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", 
                            String.Format("Basic realm=\"{0}\"", BasicRealm));
    filterContext.Result = new HttpUnauthorizedResult();
    // Watch out: returning unauthorized (401) is intercepted by default 
    // by Identity and instead returns an error page with code 200, which isn't what you want
    }
}

Use it

[BasicAuthenticationAttribute("Data Upload Realm")]
public class UploadController : Controller
{
	[HttpPost]
	public ActionResult NewRecords()
	{
		//...
	}
}

Cookies

You can set a cookie for whatever you want

  • Set-Cookie header
    set-cookie:fr=0LR4grqIfc8FVKsGb..BaikXz.6-.AAA.0.0.BaikXz.AWW6VSNR; 
      expires=Sun, 20-May-2018 03:35:15 GMT; Max-Age=7776000;
      path=/; domain=.facebook.com; secure; httponly
  • In MVC:
    Response.Cookies["userName"].Value = "patrick";
    Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
    // or	
    HttpCookie aCookie = new HttpCookie("lastVisit");
    aCookie.Value = DateTime.Now.ToString();
    aCookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(aCookie);
  • Used to store state information
  • Automatically sent by the browser with every request to that host
  • Maximum size of 4096 bytes
  • Can set up to 20 cookies (by name)
  • If expiration is not set, it's a session variable or session cookie
  • A cookie set with Secure can only be sent over HTTPS
  • HTTPOnly cookies are not accessable to Javascript, otherwise can be accessed through Document.cookie
"Confidential or sensitive information should never be stored or transmitted in HTTP Cookies, as the entire mechanism is inherently insecure." [MDN HTTP cookies]

So of course we should use it for authentication!

Response headers

Typical session

  1. Site prompts for username/password. User provides them and submits form.
  2. Request is sent using HTTPS. Username/password in form data (HTTP body).
  3. Server verifies credentials. Sets a cookie in response; either session or persistent AND stores it in the DB.
  4. On subsequent requests, cookie is sent automatically and verified against data in the DB. If OK, request is processed.
  5. When user logs out, session data in DB is destroyed or invalidated; optionally delete user cookie.

What must the server and client do to make this work efficiently and securely?

Tokens

  • Most commonly JSON Web Tokens (JWT or "jot")
  • Generally, RFC6750
  • Clients access a protected resource by obtaining and presenting an access token.
  • Tokens are strings representing access authorization
  • Does not contain primary credentials (i.e. no UserID/Password)

Where & What?

  • Using Authorization: Bearer header,
  • query strings or form data; can be stored in a cookie too
  • A cryptographically signed JSON object containing a set of claims
  • Tokens are self contained. See jwt.io

Brief explanation of digital signatures

Digital Signature flowchart

Source of image:Bitcoin: Technical Background and Data Analysis

How?

  1. User submits credentials to the server (i.e. UserID/Password)
  2. Server validates credentials, assembles JWT token with appropriate claims in the payload
  3. Server signs it using a secret key, completes the token and returns it in the response
  4. Browser stores it and sends it with each HTTP request

From: JWT: The Complete Guide to JSON Web Tokens

Each time the server receives a token in a request...

  1. server confirms the signature using previously used secret key
  2. Confirms that someone in possession of secret key signed this token, can trust it
  3. Extract claims and some identifier from payload
  4. Use them to process request
  5. Keep secret key, secret! And use HTTPS/TLS

How is this any different than cookies?

Comparison between cookie and token auth

From: Auth0

Why?

  • Enables stateless authentication and sessions (Speed)
  • Enables the separation of the authentication domain from the application domain (Scale, Design)
  • Enables 3rd party authentication (Flexibility & Features)

Rose Espiritu @ Medium.com

  • Popular with Javascript web frameworks, single page applications
  • Mobile applications
  • REST APIs
  • Internet of Things
  • Cloud services

Separation of authentication from application oodlestechnologies.com

Really shines with Server-to-Server API calls with Public Key Cryptography

Rachit Gulati @ codeburst.io

OAuth

  • OAuth 2.0 RFC6749 (2012)
  • Oauth 1.0 (2010)
  • Open Standard and Framework for Authorization
  • Big and complex
  • Used by Google, Dropbox, Facebook, GitHub, Instagram, Microsoft, ...

Authorization Flows

Oracle Fusion Middleware

Using OAuth

In .NET

  • Use Authentication/Authorization Middleware
    • Microsoft.Owin.Security.Cookies
    • Microsoft.Owin.Security.OAuth
    • Microsoft.Owin.Security.Jwt
    • ...

Other languages/platforms

Oauth.net/code

ASP.NET Identity Database Requirements

Database Diagram (.pdf) + Example in use using Option 1

Class Diagram

Class diagram of MVC application with Identity-based individual accounts