Authentication & Authorization in Web Application

Pan Chuan

2016.12.08

Why do this talk?

  • summarize the fragmental Authorization & Authentication knowledge which got during Goauth project.

Outline

  • Web Authorization VS Authentication
  • Web Authentication Main Methods
  • GoAuth brief introduction

- HTTP Basic Auth

- HTTP Digest Auth

- Cookie-based Auth 

- Token-based Auth ( JWT )

- OAuth2

Authentication answer the questions:

  •  who is the user ?
  •  Is the user really who himself claims ?

Authorization answer the questions:

  •  Is User X authorized to access resource R ?
  •  is User X authorized to perform operation P ?
  •  Is User X authorized to perform operation P on resource R ?

Concept Clarify

Contrast

Authentication

Authorization

Enter a building with badge/fingerprint/retina scan

Login into a forum with username and password

allow to enter a door

Edit yourself's thread

Edit other people's thread

HTTP Status Code 401 vs 403

  • Related to authentication 
  • No credential or wrong credentail 
  • Semantically "unauthenticated" should be more accurate
  • Related to authorization
  • The server understands the request, but refuse to fulfill it.

401 Unauthorized:

403 Forbidden:

Tips about A&A

 

  • Authentication always proceeds Authorization. 

 

  • We have paradigm for Authenentication, but no common rules for Authorization. Authorization highly depends on your business logic.

 

  • Both unproper Authentication and Authorization can bring severe security issues to your Application.

Real Example: Authorization  Vulnerability in Rakuten Books

https://books.rakuten.co.jp/mypage/delivery/receiptPrint?order_number=213310-20160914-0910455279&back_number=2f4c0b5b26845f788d71377383113a26efdd61b68fd5595771663b066a35a02c&shippingId=82719971&customerName=Pan%E3%80%80Chuan​

82719981 can work.

receipt page url:

receipt page pdf:

You have access to see everyone's receipt..

  • NEVRE trust the request from client.

  • ALWAYS check the real authorization after the authentication pass.

Keep In Mind

Stateless REST APIs

Client

DELETE http://myapis.com/v1/res/456

userid="111"

Need check again if userid '111' can really delete resource  456 by querying DB/ACL.

123

789

Http Basic Authentication

 

GET /someresource/ HTTP/1.1
Host: www.hostname.com
Authorization: Basic aHR0cHdhdGNoOmY=

Base64(<username>:<password>)

  • The simplest technique for enforcing access control to web resources.
  • Use standard field in the HTTP header, avoid cookies, session identifiers or login page
  • Super simple but not secure, always use HTTPs for HTTP basic auth

Http Digest Authentication

 

  • Secure version of http basic auth.
  • Don't send password plaintext, send username and MD5 hash 

client

server

init request

401 return, nonce

send[ username,nonce,MD5(nonce,username,URI,Method,password)]

200

1) look up password from DB

2) re-compute MD5 and compare

real Http Digest is more complex than this simple version diagram, please check the wikipedia

cookie-based Authentication 

cookie-based Authentication 

  • Cookie-based Auth is stateful.

  • Backend servers need to share/sync all sessions if multiple service instance are running.

  • The server needs to keep track of active sessions in a storage(Framework context/DB/Redis).

Token-based Authentication 

  • Token-based authentication has gained prevalence over the last few years due to rise of single page applications, web APIs, Mobile Apps and the Internet of Things(IoT).
  • Token-based authentication works by ensuring that each request to a server is accompanied by a signed token which the server verifies for authentication and only then resonds to the request.

Token-based Authentication 

Same Step 1 as Cookied-based

Token-based Authentication 

Mechanism

token = user_id |  expiry_date | HMAC (user_id | expiry_date, secret)
  • Using a hash mechanism e.g HMAC-SHA1
  • Encrypting the token symmetrically e.g AES
token = AES(user_id | expiry_date, key)
  • Encrypting the token asymmetrically e.g RSA
token = RSA(user_id | expiry_date, private_key)

Introducing JWT

  • Json Web Token is a open stardard (RFC7519) for creating access tokens that assert some number of claims. The claims are encoded as a JSON object that is digitally signed by hashing it using a secret that only know by server.

 

  • A secure way to encapsulate arbitrary data that can be sent over unsecure http connection.

 

  • While there are different ways to implement tokens, JWT has become the de-facto stardard.

JWT string

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

{
"typ": "JWT",
"alg": "HS256"
}
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Header Json:

Payload Json:

Signature: HMACSHS256(base64(header) + "." + base64(payload),"secret")

Payload: base64(payload)

Header: base64(header Json)

  • JWT Token is signed,not encrypted.

JWT diagram

JWT benefits

  • Stateless, Scalable and Decoupled
  • Performance
  • Cross Domain and CORS
  • Mobile Ready

- backend does not need to track tokens, each token is self-contained

- save sessions' storage

- decoding jwt is faster than lookup DB/Cache for session query.

- Native mobile platforms doest mix well with cookie,

- cross domain headache is gone.

What else can JWT be useful?

  • To archieve Single Sign-on.

- Sharing the Jwt between different applications.

  • Whenever you need to securely send a payload.

  • Generate "one click" action url link.

- Eg: to obscure URL parameters or POST body.

 JWT one-click example

  • Scenario:A followed B, Website nofitys B by Email and provide a link to let B also follow A

https://your.awesome-app.com/make-friend/?from_user=B&target_user=A

https://your.awesome-app.com/make-friend/?jwt=aaa.bbb.ccc

{

   “expire”:1441594772,

   "sub": "B@example.com",

   "aud": "www.example.com",

   "from_user":"B",

   "target_user":"A"

}

jwt payload part:

Not Good,

Need login first

Good,

One Click

Best practice about JWT 

  • Keep the Key secret.
  • Don't add senstive data to the payload.
  • Give token an expiration.
  • Embrace HTTPS.

the jwt token is valid forever unless the signing key is changed or expration explicitly set.

payload text is just base64 encoded.

the signing key should be treated like any other credentials and revealed only to services that absolutely need it.

Recap 4 Authentication Methods

  • HTTP Basic Auth

- simple but not secure

  • HTTP Digest Auth

- secure but usage is limited

  • HTTP Cookie-based Auth

- flexible/powerful but resource cost

  • HTTP Token-based Auth

- balanced and widely scenario support

OAuth2 Introduction

  • The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.

OAuth2: Roles

Resource Owner: the person or the application that holds the data to be shared.

Resource Server: the application that holds the protected resources.

Authorization Server: the application that verifies the identity of the users.

Client: the application that makes request to the Resource Server on behalf of the Resource Owner.

OAuth2: workflow

rfc 6749:

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

I want to see a list of photoes

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Hi, RS, could you give me a list of photoes?

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Sorry, this is a protected resource, You

need an access token.

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Hi AS, can I get an access

token? RS is asking.

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Sure, But I need to ask some

details to the user first.

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Hi, Could you provide your credentials?

I need to verify your identity

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

No problem, I am snow@gmail.com and my

password is secret

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

The user is who claims to be,

Here is your access token: yGH38dee0oHN72Dyen3

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Hi Backend,

Here is my token: yGH38dee0oHN72Dyen3

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Hi I have been give token: yGH38dee0oHN72Dyen3

can you tell me who it belongs to?

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Of course, the token is valid and it belongs to:

snow@gmail.com

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Everything is allright, This is the

list of photoes,enjoy!

OAuth2: Example

Resource Owner

Authorization Server

Resource Server

Client

Here you are the list of photoes, enjoy!

Resource Owner

Client

OAuth2 works as a delegation way, as the Client has no idea about the credentials of the Resouce Owner

OAuth vs JWT

  • They are totally different things, not comparable.

  • JWT is a type of token, OAuth is a framework that describes how to dispense tokens. Apple VS Apple Carts !

  • JWT can absolutely be used as an OAuth bearer token. (the most common practice RFC7523)

GoAuth introduction

  • GoAuth provides an independent authentication layer between multiple services. It can also return some simple metadata for authorization usage to the caller.
  • GoAuth's main task is doing authentication, helps to do authorization for avocation.

GoAuth workflow

OrderAPI

 

ItemAPI

 

ShopAPI

 

 

GoAuth

 

rmsX microservices:

Some Client

1.apply key

2.request with key

3.validate key

GoAuth Authentication

  • Weak Validation Type: (similar with HTTP Basic Auth )
  • Strong Validation Type: (similar with HTTP Digest Auth)
Authorization: serviceId Key:Signature
Date: 2016-12-11T15:03:24Z

Requst Header:

Requst Header:

Authorization: serviceId Key

Signature = Base64(HAMC-SHA1(APISecret, StringToSign))

StringToSign = Date + " \t" + ReqURI + "\t"+ ReqMethod

GoAuth Authorization

  • Goauth Validation API can return Key's metadata to caller to help doing high-level authorization.
  • Each key's Metadata is pre-defined by service admin via Goauth back-stage system.
{
    "StatusCode": 200,
    "Message": "Validate successfully.",
    "Metadata": {
        "RoleName":"General Engineer",
        "UserName":"chuan.pan@rakuten.com",
        "ResourcePermission":[
            {"Resource":"order/find", "Methods":["GET"]},
            {"Resource":"order/get", "Methods":["GET"]},
            {"Resource":"order-detail/add", "Methods":["POST"]},
        ]
    }
}

Summary

  • Authentication vs Authorization
  • Authentication methods

- Http Basic Authentication

- Http Digest Authentication

- Cookie-based VS Token-based Authentication

  • GoAuth project introduction

- Oauth2 VS Jwt

Thanks

Q&A

A&A

By panchuan

A&A

  • 1,122