Вы находитесь на странице: 1из 169

Three Auth Protocols and Three Shakespeare Tragedies

Created by
kourcul@protonmail.com
September 2016

1
Three Auth Protocols and Three Shakespeare Tragedies

Hear ye!, hear ye!


The bard has came to life here
And three protocols hast brought with him

This is no ordinary cybersecurity leaflet, though its humble author has tried to
deliver simple and easily understandable explanations (something not out of the
ordinary) the presence of the immortal bard makes this story to be told as no
other has been told before (at least among the ones related to the topics). Thats
the effect Ive been seeking and thats the result I hope comes to.

In the cybersecurity documentary realm I have always been told to start with an
objective and scope. Not sure if in order to introduce the document itself or
just to fill one more page in reports which were paid by weight. I will invest in it
no more that the following paragraphs. Ignore them if you know what these
protocols are used for or if you want to delve directly into the gory details, but
let me tell you anyway that this document does not provides the deepest
immersion into technical details of protocols. Some technical details which may
vary depending on implementations (mostly in SAML) are not shown, becaue
covering all possible options would take years and gives no further insight. The
idea is to give the neophyte user an overview of the pieces working together, and
to some advanced users a simple guideline about parameters, flows and
specification references.

Three Auth protocols are the main topic in this play. I refer them as Auth because

2
Three Auth Protocols and Three Shakespeare Tragedies

they are indistinctly Authentication or Authorisation (some to one, some to the


other, some to both) and if I were to be exquisitely accurate with these terms in
the title it would have been too long. The protocols are so called federated
protocols or federated scheme protocols and are nowadays widely used because
they transcend older auth paradigms such as the Distributed Access Control
(a.k.a. the inner circle of hell where nasty security admins must manually manage
trillions of objects each one with a different ACL) and the Centralised Access
Control (a.k.a. the outer circle of hell where another kind of admins have to
forever fight the Kerberos and the unique points of failure); therefore this new
protocols rise with the backdrop of new computer scenarios (the Clouds, the Fog,
Big Data, IoT,) where federation means a multi-party scenario with selective
and consolidated trust channels which have to be established following a
predetermined standardised sequences of steps carried by the different parties.

Does this mean they are better? More secure? With a better throughput? Nay,
they are just a different approach (probably THE different approach very much
needed), but they have come to stay and as it tends to happen in computer
security- to evolve as new tech trends are born.

These three Auth protocols we are playing with are the following:

- SAML 2.0
- OAuth 2.0
- OpenID Connect

And why the tragedies? Well, see them as a wiseguy narrative resource. This is no
ordinary cybersecurity leaflet, remember?

2
Three Auth Protocols and Three Shakespeare Tragedies

SAML 2.0 (Security Assertion Mark-up Language) is the first Auth protocol
were pushing to scene. It provides a framework for security data exchange, both
auths, between an asserting party and a relying party (well see later on about
these terms). Its structures are XML-based and it has been created by the OASIS
Security Services Technical Committee in 2001, though it was not until the 2005
update when it came to fame, with version 2.0.

SAML mainly addresses the problem of web-based multidomain single sign-on


services, transcending the need to rely solely on cookies. More than 90% uses I
have seen refer to this SSO issue (we will call it profile soon enough). This
problem can be approached as a delegation or as a federation, it depends on the
context and the custodian of credentials.

To carry out this scenarios a trust relationship between parties is needed; but as
some witches could say: fair is foul and foul is fair (or was it the other way
round?), how do you establish this trust? Which kind of ring seals this marriage?
Ill tell you; the Metadata.

You can see metadata as the way in which the different parties involved in the
Auth procedures strip their souls, or take an oath of collaboration with each
other. In metadata it is expressed which and how security configurations and
features are supported; for example: an entity's supported SAML bindings,
operational roles (IDP, SP, etc.), global identifier information, supporting identity
attributes and key information for encryption and signing can be expressed

3
Three Auth Protocols and Three Shakespeare Tragedies

using its own XML schema. Metadata exchange is a required and mandatory step
to enable SAML communication between parties, how this exchange is made is
not specified in the standard documentation and neither in any security guideline
that Ive found. Feel free to contact and correct me, NIST experts!

We will not delve further into metadata structures in this document (feel free to
explore the detailed 40 pages long document OASIS has available in their site)
although some details of their contents will be mentioned now and then between
acts.

As we are talking about literature and cybersecurity here, I shall mention a few
good practices that should be taken as commandments if you are to implement
any SAML profile in your organization (well visit them sometime later again):

Thou shalt implement SAML through TLS 1.0 or SSL 3.0. Keep your
communication channel confidential. Bilateral authentication via digital
certificates is considerably recommended but not mandated.
Thou shalt digitally sign SAML assertions delivered via POST methods,
specially assertions containing response messages.

So shall all this be used as an introduction.

Here starts the travel to SAML 2.0, and this travel starts in 10th century Scotland,
after an enraged rebellious battle; the bloodier, the better.

3
Three Auth Protocols and Three Shakespeare Tragedies

So there was once upon a time this brave Scottish thane returning to see his king.
Faithful, fair and strong as no other has been seen fighting the invader from
Norway and Ireland army. His war deeds are uncompared for. It seems he
himself has quenched the thane of Cawdors traitorous intent with gallons of
blood shed in the battlefield. He is accompanied by his friend Banquo, who is
also a general, but not nobleman enough to be the main character in the play.

And so when they were wallowing in the bloody victory on their way to meet
King Duncan, their paths take them to bump into three sisters witches in the
middle of a heath (where else could one meet witches). This ladies receive them
with prophecies which foretell the titles soon to be bestowed upon Macbeth;
Thane of Cawdor. And King hereafter.

A stunned Macbeth, lost in wondering thoughts, would cross paths a few


moments later another thane who came to announce him his newly bestowed
title. Yes, you guessed ok; Thane of Cawdor. Imagine the greedy eyes glittering
with kingly plans of future. Three women came to a dutyful man and change his
life forever giving birth to one of the bloodiest stories ever written.

See the analogy here. Macbeth and Banquo go with information of a fulfilled
service to the crown, their provider of titles, and in their way they are
redirected in a heath to an element which asserts titles and identities. With this
new yourself, who has been always the same person but now there is proof of
your identity, the reporting of the battle is carried out in front of king Duncan.

4
Three Auth Protocols and Three Shakespeare Tragedies

Lets review this story with different terms and perspective. Macbeth and
Banquo are users (consumers of an information service) who want to update an
status about an extinguishing rebellion. This update can only be carried out in
the proper available service; the kings court in front of Duncan himself and all of
his chancellors. On the way there, suppose they are redirected to meet the
witches (not by a HTTP 302 redirect message, but because they are drunk with
victory and spirits), and this witches are a trustworthy (ahem, ahem. Imagine! I
say) source of authorised prophecies and roles. They provide with identity
details and claims to the users Macbeth and Banquo. Only with this issued
proofs of identity can a service be accessed at the provider; Duncans court at
Dunsinane. And so the information update is delivered only by the properly
authorised and identified users.

As the witches here act as an Identity provider (or IdP) they assert the proofs of
Auth to the users, they are the Asserting Party. Macbeth and Banquo are the
users who rely on the assertions cast by the witches, so they are the Relying
Party. This are standard terms in SAML protocol and are important to
understand how this protocol operates, but they could be extrapolated to any
other similar authentication scenario. The third part involved is the Service
Provider, which represents the main access controlled object custodian which the
users intend to reach from the beginning.

So if Macbeth gets the straight prophecy and is now more Thane than before and
King hereafter, What about Banquo? Well, he receives the paradoxical prophecy:

5
Three Auth Protocols and Three Shakespeare Tragedies

Less than Macbeth and yet happier, not king and yet father of a line of kings
Can you imagine Macbeths face after this last line?

Witches, crone or sultry, always causing strife and breeding quarrels among
brothers in arms.

5
Three Auth Protocols and Three Shakespeare Tragedies

The SAML core specification describes, at a XML design level, the constructs
which form the security context used to exchange data between parties.

The core construct in a SAML communication is the Assertion. Assertions


contain one or more statements and some common information that applies to all
contained statements or to the assertion as a whole. Assertions are carried in
response messages and usually contain delicate information (according to
confidentiality and integrity terms), therefore response messages should be, at
least, digitally signed and broadcast in an encrypted channel.

A SAML protocol describes how SAML elements are packaged within SAML
request and response elements. Only appropriate requests can produce
appropriate responses (as happens with everything called protocol) by following
a XML-defined schema. Requests consists mainly of queries and responses of
assertions.

SAML bindings define means of mapping this request-response protocol


messages onto standard messaging or communications protocols (HTTP,
SOAP,). An instance of mapping SAML request-response message exchanges
into a specific communication protocol is termed a binding for SAML or a SAML
binding (fair is foul, foul is fair).

Finally, SAML profiles are the use cases each defined to address a different
problem which we want to solve by using the SAML features. The most widely

6
Three Auth Protocols and Three Shakespeare Tragedies

used is the Web Single sign-on profile. This document describes in detail Web
SSO and Single logout profiles. You can see profiles as the flows of bindings
required to solve a business case.

Assertions are separate pieces of dialogue, Protocols are acts, Bindings are scenes
and profiles are the full play. As you see in the image, these elements are self-
inclusive like Russian dolls. When correctly boiled in the witches cauldron
following the appropriate profile recipe a SAML flow is created.

6
Three Auth Protocols and Three Shakespeare Tragedies

Assertions carry the statements claimed as true by the asserting party for a
delimited period of time. They are usually sent from IdP to SP and there are (in
SAML 2.0 version) three different types:

- Authentication assertions: Carry statements claiming that the principal or


user has correctly and successfully authenticated with the Identity provider,
and how and when was it done.

- Authorisation assertions: Carry statements claiming that a determined action


can be dome by the principal in the service provider. This kind of assertion
has been quickly overpassed by attribute assertions and XACML; a much
more specific protocol (also XML-based) for authorization information
exchange used in ABAC (Attribute-based access control) environments.

- Attribute assertion: Carry simple name-value or key-value attribute pairs.


This attribute can be used as a role which the parties can understand instead
of using authorisation assertions.

7
Three Auth Protocols and Three Shakespeare Tragedies

This is an example of Authentication Assertion taken from the OASIS SSTC


Security Assertion Markup Language (SAML) V2.0 Technical Overview Document.

Line 1 begins the assertion and contains the declaration of the SAML assertion
namespace, which is conventionally represented in the specifications with the
saml: prefix.
Lines 2 through 6 provide information about the nature of the assertion:
which version of SAML is being used, when the assertion was created, and
who issued it.
Lines 7 through 12 provide information about the subject of the assertion, to
which all of the contained statements apply. The subject has a name identifier
(line 10) whose value is j.doe@example.com, provided in the format
described on line 9 (email address). SAML defines various name identifier
formats, and you can also define your own.
The assertion as a whole has a validity period indicated by lines 14 and 15.
Additional conditions on the use of the assertion can be provided inside this
element; SAML predefines some and you can define your own. Timestamps in
SAML use the XML Schema dateTime data type.
The authentication statement appearing on lines 17 through 24 shows that
this subject was originally authenticated using a password-protected transport
mechanism (e.g. entering a username and password submitted over an SSL-
protected browser session) at the time and date shown. SAML predefines
numerous authentication context mechanisms (called classes), and you can
also define your own mechanisms. The <NameID> element within a

8
Three Auth Protocols and Three Shakespeare Tragedies

<Subject> offers the ability to provide name identifiers in a number of different


formats. SAML's predefined formats include:
Email address
X.509 subject name
Windows domain qualified name
Kerberos principal name
Entity identifier
Persistent identifier
Transient identifier

8
Three Auth Protocols and Three Shakespeare Tragedies

This is an example of Attribute Assertion taken from the OASIS SSTC Security
Assertion Markup Language (SAML) V2.0 Technical Overview Document.

A single statement can contain multiple attributes. In this example, there are
three attributes (starting on lines 2, 10, and 16) within the statement.

Attribute names are qualified with a name format (lines 4, 11, and 17) which
indicates how the attribute name is to be interpreted. This example takes
advantage of two of the SAML-defined attribute profiles and defines a third
custom attribute as well. The first attribute uses the SAML X.500/LDAP
Attribute Profile to define a value for the LDAP. This attribute in an LDAP
directory has a friendly name of givenName and the attribute's value is
John. The second attribute utilizes the SAML Basic Attribute Profile, refers to
an attribute named LastName which has the value Doe. The name format of
the third attribute indicates the name is not of a format defined by SAML, but is
rather defined by a third party, SmithCo. Note that the use of private formats
and attribute profiles can create significant interoperability issues.

The value of an attribute can be defined by simple data types, as on lines 7 and
14, or can be structured XML, as on lines 20 through 22.

9
Three Auth Protocols and Three Shakespeare Tragedies

Protocols wrap SAML assertions in order to form the request-response elements


of communication. The most used protocols follow this request-response model,
but some others consists only of a request that triggers an specific action (like
changing the handler of a principal) or asks for further assertions. A single
profile can be formed by several protocols nested one in another; for example,
the Authentication request protocol can trigger an assertion query and response
protocol, so the former cannot be finished until the latter has been successfully
ended.

10
Three Auth Protocols and Three Shakespeare Tragedies

Bindings define how protocols messages can be sent and received using common
protocols. Although the mechanism is similar we are not going to cover SOAP
bindings extensively, but only the common HTTP ones. There are two of this
kind (four really, but HTTP Artifact resolutions can be approached as variations
of the other two).

Artifacts are just code or text snippets of fixed length understood only by the
end peers of the communication but not by the SAML protocol itself. Where
other bindings (or protocols, or profiles) just use values, Artifact ones use
references to the artifact itself or what it contains.

Why HTTP and not SOAP? Because HTTP is a standard more widely used and
well-known than SOAP, whose uses are extremely efficient, but circumscribed to
a set of cases and middleware environments heavily reliant on ESP or special
service buses (SOA). Also we want to focus on communication flows happening
in the front-channels, which mostly travel close to the user agent browser, and
not in the back-channels, where SOAP is more alive. Anyway we will show
some examples where SOAP is mentioned.

It is like asking why Macbeth and not Titus Andronicus.

11
Three Auth Protocols and Three Shakespeare Tragedies

And finally profiles, which orchestrate the way in which the other elements are
combined and play together.

By far, the most represented profile is the Web browser single sign on. Other
profiles are derived from it, though not all of them. It addresses the issue of a
browser (relying party) authenticating in an identity provider (asserting party)
trusted by a service provider, with the particularity that this IdP does not need to
belong to the SP, it just need trust. This way the credential custodian is only the
IdP in the whole scenario, making SP services available to users without having
to create credentials for all SP sites.

This trust is forged by a Metadata exchange, which defines the game rules and
what a party can expect from the other ones. In the heath, the witches traded in
with prophecies, Macbeth and Banquo with astonishments (for the moment).

12
Three Auth Protocols and Three Shakespeare Tragedies

The web single sign on profile comes in two flavours, depending on which
provider starts the SAML dance. They are mutually excluding. Lets start with
the service provider initiated flow.

Remember our first scene with Macbeth, Banquo and the Witches? We go back
there now.

13
Three Auth Protocols and Three Shakespeare Tragedies

In the first step Macbeth (the user agent) travels innocently to meet king Duncan
(The service provider) to deliver an update after a battle.

The service provider should look up if it has already a security context for this
user agent. If he has not (as in this case) then he must create it by looking for the
appropriate Identity provider. Remember that SP and IdP have exchanged
metadata and they have a previous notion of how each other can interact, or else
there are discovery but what happens if our SP is a bit promiscuous and
entangles in unclean and unchristian relationship with several IdP?

Service providers store a base64 encoded cookie (labelled _saml_idp) where the
different trusted IdP are uniquely identified. Should you, reader, ever be very
much mandated to deploy a SAML compliant service provider, swear by your
honour that this cookie you shall mark as secure.

14
Three Auth Protocols and Three Shakespeare Tragedies

The user agent is therefore redirected to an Identity provider. In the image I use a
HTTP Redirect binding, which expels a HTTP 302 or 303 to the user agent, but it
could be a HTTP POST binding either way. If I have chosen the redirect binding
is because it is most widely used in this profile.

The 302 redirection modifies the URL as follows:


It MUST append a SAMLRequest parameter to the URL containing the
DEFLATE encoded AuthnRequest message.
It MAY append a RelayState parameter to the URL containing a token or
fixed value that the IdP must return to the user agent with exactly the same
value along with the response.

For SP-initiated SSO, the RelayState it's a mechanism for the service
provider to maintain state information between sending the AuthnRequest
and receiving the SAML response and thus thwarting CSRF attacks.

15
Three Auth Protocols and Three Shakespeare Tragedies

This slide illustrates an example of decoded AuthnRequest contained in a


SAMLRequest provided by the OASIS SSTC Security Assertion Markup Language
(SAML) V2.0 Technical Overview Document.

The answer or response to an AuthnRequest must be an authentication


assertion.

AssertionConsumerServiceIndex field indicates where the response must be


sent. Here it is referred with a code that the IdP understands (its been informed
in the metadata exchange). It applies only to profiles, like this one, in which
the requester is different from the presenter. Would it not be defined by
indexes, an URL may be used by AssertionConsumerServiceURL field
instead. These two attributes are mutually exclusive and both are optional.

In this example the AllowCreate is set to true permits the identity provider to
establish a new transient identifier for the principal if none exists. If
absent, default is false. This is included in the NameIDPolicy tags, whose
name is very self-explaining.

17
Three Auth Protocols and Three Shakespeare Tragedies

The Identity Provider must then check if a security context according to the
AuthnRequest policies exists. If not, it challenges the user to authenticate by
means out of scope of the SAML standard.

Username and password are the most common. In the picture QR authentication
is also featured.

18
Three Auth Protocols and Three Shakespeare Tragedies

Login credentials are checked in the IdP, which is the main authentication
authority in this game as you should have guessed by now. If OK, a security
context is created.

The security context must then be communicated to the user agent by means of
an assertion (or a prophecy in case of the witches). This data does not carry
credential information but it is prone to MITM tampering, priority here is to
maintain integrity of the message by adding a digital signature.

19
Three Auth Protocols and Three Shakespeare Tragedies

As we said before, the assertion is signed because it is going to be conveyed by


an HTTP POST Binding. Depending on the SAML implementation, only the
assertion is signed or all the Response (which includes de assertion in its
structure) is signed.

The SAMLResponse included is base 64 encoded in a HTML FORM as a hidden


field. If a RelayState was received it is included as another field in the form and
it must be exactly the same value received.

20
Three Auth Protocols and Three Shakespeare Tragedies

Geeyou see the picture, dont you?... a bit more complex than the request, isnt
it? Witches and Prophecies is what they have.

Some of the most relevant tags worth mentioning here are the following:

Status: Code representing status of the request (pretty straightforward). At least


a value StatusCode is required, where the operational result is announced, it
may contain a success value or several others, each one representing a different
error type. Optional values in the Status tags are StatusMessage (a string to
return to the user) and StatusDetail (carrying additional information). As this is
a security document, the less details sent to the user, the better.

Assertion: Core of the response message. Some of the subtags in Assertion are:
- Signature: Digital signature of the assertion to maintain integrity. It may be
out in an upper level calculated over the whole Response.
- Subject: Principal who is related to the statements in the assertion-
- NameID (also BaseID or EncryptedID): Identifies the subject
- SubjectConfirmation: Conditions under which somebody trying
to use the assertion is permitted to do so. Depending on the
SAML implementation these conditions may vary, but the OASIS
profile specification mentions three of them:
- Bearer: the most common. Subject of the assertion is the
bearer of the assertion.
- Holder-of-key: Introduces the use of public key

21
Three Auth Protocols and Three Shakespeare Tragedies

cryptography. One or more elements ds:KeyInfo MUST be


present within a element SubjectConfirmationData. By
embedding a public key inside a Holder-of-
key SubjectConfirmation , the issuer enables a client that can
prove ownership of the key to use the assertion. It becomes
not only a stand-alone package of information but also a
security token. Key values can be transmitted with
modulus and exponent separately.
- Sender-vouches: Indicates that no other information is
available about the context of use of the assertion. The relying
party SHOULD utilize other means to determine if it should
process the assertion further.
- Conditions: Placement of constraints for the use of the assertion (NotBefore,
NotOnOrAfter, audience restrictions, one time use,)
- AuthnStatement: Confirms how (with an AuthnContext field) and when (with
an AuthnInstant field) the assertion subject was authenticated.

21
Three Auth Protocols and Three Shakespeare Tragedies

The browser, due either to a user action or, more usually, by execution of an
auto-submit script, issues an HTTP POST request to send the form to the SP's
Assertion Consumer Service. Values of the SAMLResponse and RelayState
parameters are taken from the HTML hidden form.

For ease of use purposes, the HTML FORM typically will be accompanied by
script code that will automatically post the form to the destination site.

22
Three Auth Protocols and Three Shakespeare Tragedies

The service provider's Assertion Consumer Service obtains the message from the
HTML FORM for processing. The digital signature on the SAML assertion must
first be validated and then the assertion contents are processed in order to create
a local logon security context for the user at the SP.

But how does the SP validate the signature?

23
Three Auth Protocols and Three Shakespeare Tragedies

Yes, Trust. The SP must have a public key belonging to the IdP in order to
validate signatures. Metadata included in the initial exchange contains an IdP
digital certificate.

Trust relationship, remember?

24
Three Auth Protocols and Three Shakespeare Tragedies

Once this flow completes and the security context is created, the SP sends an
HTTP redirect response to the browser directing it to access the originally
requested resource.

And thats it.

25
Three Auth Protocols and Three Shakespeare Tragedies

This is the full flow as illustrated in the SAML V2.0 Technical Overview
document by OASIS.

26
Three Auth Protocols and Three Shakespeare Tragedies

What have we seen up to now? SAML Web browser SSO profile SP-Initiated,
using first a Redirect binding for the request and a POST binding for the
response.

So now Macbeth has reached Duncan to update him with the battle status, but
Duncan already knew it. Whatever, thought Macbeth, duty accomplished; and
now time to think about the prophecies. Remember the witches telling Macbeth
he will be king someday (but when? He wonders) and Banquo being father of
kings (but how and why? He wonders again).

The bloodiest and boldest determination comes to his mind, not without
suggestion from Lady Macbeth, and two ominous killings does he commit. One
by his own hands, the other by hiring three murderers.

Is this a dagger which I see before me,


The handle toward my hand? Come, let me clutch thee.
[]
One cried, God bless us! and Amen the other,
As they had seen me with these hangmans hands.
List'ning their fear I could not say Amen,
When they did say God bless us!

And thus Macbeth became king of Scotland as kinsman of the dead king. All hail
king Macbeth!

27
Three Auth Protocols and Three Shakespeare Tragedies

Blood has started to flow, as wine and merriment in the royal banquet the new
king hosts, and there something singular happens; the ghost of a late friend
appears.

27
Three Auth Protocols and Three Shakespeare Tragedies

Banquos ghost appears in the banquet hall and sits as one more of the lords,
only visible to the murderous king and queen, and it sits in Macbeths chair.
First he thinks its a disrespectful joke, later he will be scared of something that
would scare the devil itself. The ghost does not speak, for the dead dont do, it
only nods once and again, and this gets to the kings nerves. It is the queen who
struggles to maintain the appearances, calms her husband and keeps the lords in
their seats. The ghost departs, the noblemen drink. and the ghost returns
again.

No excuse and no lady Macbeth can contain the king now.

Quit my sight! Let the earth hide thee.


Thy bones are marrowless, thy blood is cold.
Thou hast no speculation in those eyes
Which thou dost glare with!

The king rages against the chair and the lords get startled and suspicious (if they
were not yet). Macbeth crime suspicions are talk of the day. Also, if there were
not hints enough, Banquos and Duncans sons have fled. What seemed to have
become an easy and happy existence under the crown has disturbingly proved
not to be so.

What does our treacherous king do to find a solution to his anxiety and remorse,
to this incipient and violent madness accursing him? He goes a pays a visit to the

28
Three Auth Protocols and Three Shakespeare Tragedies

ones with whom his ambitions started; the three witches.

28
Three Auth Protocols and Three Shakespeare Tragedies

In the beginning of the first act, it is Macbeth who goes to get a resource and is
directed to the witches who act as IdP to authenticate and know about his future.
Now in the end of act three and beginning of act four, Macbeth himself goes to
the witches first to be afterwards directed to the service (he wants advise and
new prophecies). The path is changed as the SAML flow is changed.

This is the essence of the IdP-initiated SAML flow. In an IdP-initiated use case,
the identity provider is configured with specialized links that refer to the desired
service providers. These links actually refer to the local IdP's Single Sign-On
Service and pass parameters to the service identifying the remote SP. So instead
of visiting the SP directly, the user accesses the IdP site and clicks on one of the
links to gain access to the remote SP.

29
Three Auth Protocols and Three Shakespeare Tragedies

In the first step, the browser requests a service or resource through the IdP
directly provided it is linked is its front services. The browser has not a
security context yet in the IdP.

For IdP-initiated flow, the RelayState usually specifies the landing page at
the service provider once the single sign on completes.

30
Three Auth Protocols and Three Shakespeare Tragedies

The IdP challenges the user for credentials to initiate a security context.

31
Three Auth Protocols and Three Shakespeare Tragedies

User provides credentials.

For the prickling in my hands,


something wicked this way comes.
Open locks! To whoever knocks

32
Three Auth Protocols and Three Shakespeare Tragedies

The IdP checks credentials and, if correct, constructs the SAML Response
digitally signed and encloses it in an HTTP POST hidden form. The security
context is then created.

The resource URL at the SP is usually also encoded as the RelayState field.

The form is sent to the browser, this part related to the response works like in a
SP-initiated flow.

Security concern: Gee. See how easy could be to trick the innocent user into
clicking a forged SAML IDP-Initiated link with a custom RelayState parameter in
order to lead him or her into a false website and steal the security context. The
OASIS SAML text says that it is the SP the one who should manage RelayState
parameters, being transparent for the IdP, but from a security point of view, if
you manage the IdP filter, remove or at least control (whitelist) the RelayState
parameter. Another way to perform this and avoid some of the attacks relies on
passing the RelayState parameter via HTML form (POST method), and not in the
url (GET method); most IdPs let you set a ruleset in order to allow only POST
method.

33
Three Auth Protocols and Three Shakespeare Tragedies

The browser, due either to a user action or execution of an auto-submit script,


issues an HTTP POST request to send the form to the SP's Assertion Consumer
Service.

OASIS documentation (from where the HTTP message snippet in the illustration
is taken) also refers RelayState content as token in IdP-initiated flows, but
remember it usually contains the resource URL in the SP. Anyway, it does not
mean that it could not be used as an anti-CSRF token but the easiness to thwart
this safeguard would be trivial.

34
Three Auth Protocols and Three Shakespeare Tragedies

The service provider's Assertion Consumer Service obtains the message from the
HTML FORM for processing.

The digital signature on the SAML assertion must first be validated, and then the
assertion contents are processed in order to create a local logon security context
for the user at the SP. Once this completes, the SP retrieves the RelayState data to
determine the desired application resource URL and sends an HTTP redirect
response to the browser directing it to access the requested resource

35
Three Auth Protocols and Three Shakespeare Tragedies

The browser access the resource, and so, Macbeth gets an insight into his future.

36
Three Auth Protocols and Three Shakespeare Tragedies

Easier in implementation (at first sight), faster and lighter; but also less intuitive
for the user than the SP-initiated flow.

In the image you can see the whole flow as illustrated by the OASIS
documentation

37
Three Auth Protocols and Three Shakespeare Tragedies

This profile is still Web single Sign-on, but IdP-initiated. The example only used
the POST binding because no initial redirection to the IdP is required as in the
SP-Initiated.

What exactly did the three witches foretell Macbeth? Three warnings, prophecies
or advices the wicked king receives:

- Beware of MacDuff, the loyal (to Duncan) Thane of Fife.


- None born of woman born shall harm Macbeth.
- Macbeth will be safe until Great Birnam Wood comes to Dunsinane Hill.

So now the king feels invulnerable. How can a man not born from woman exist?
Nonsense! What madness is that of a forest walking? More nonsense! MacDuff?
He is only a man, and has just fled into exile; but just in any case raze and
plunder his castle, put all his family to death, let the blood flow on.

The king returns home bearing a triumphant gleam in his eyes, those which a
day ago were beholding his best friend ghost. He tells the queen and then both
sit proudly and reassured in the throne of Scotland. Lots of blood on their hands,
lots of sins in their souls, but king and queen either way. What can thwart such a
glorious reign?

Well Remorse can.

38
Three Auth Protocols and Three Shakespeare Tragedies

How do you run away from things that are only on your head?

Lady Macbeth stoicism crumbles and collapses. She who had been the most
manipulative and ice-hearted woman.

She sees her hands continuously blood stained, and not only metaphorically.
Washes them obsessively but sees blood which doesnt clean, and if they clean,
the blood comes back.

Out, damned spot! Out I say!

In the night, her nightmares make her sleepwalk. Stumbles along her castle
mumbling of her crimes. Now king and queens crimes are evident, all servants
know about them. Noblemen will know soon too.

When conscious of her situation, she breaks. She sees only an escape; to logout of
her life.

39
Three Auth Protocols and Three Shakespeare Tragedies

The Single Logout profile is used when the IdP acts as a session manager with
the security contexts that were created (by that same IdP) for a user in different
SPs, for example by being the authorised cookie issuer, in order to end near-
simultaneously all sessions the user has among all SPs depending on this IdP.

The logout procedure can be initiated by the user (by manually clicking on a
logout button) or by the IdP unilaterally (for example when the authentication
context expires). The flow described in the following pages describe the former
for being this more complex, the later would follow the same steps starting from
the fourth one.

This profile also allows many combinations depending on the implemented


bindings. The profile allows the protocol to be combined with a synchronous
binding, such as the SOAP binding, or with asynchronous "front-channel"
bindings, such as the HTTP Redirect, POST, or Artifact bindings. A front-channel
binding may be required, for example, in cases in which a principal's session
state exists solely in a user agent in the form of a cookie, and a direct interaction
between the user agent and the session participant or session authority is
required (the logout button click).

The OASIS documentation recommends the use of front-channel bindings for


this profile, as will be shown in this example.

Returning to our tragedy, in this case the browser role is not represented by the

40
Three Auth Protocols and Three Shakespeare Tragedies

king, but by the queen.

40
Three Auth Protocols and Three Shakespeare Tragedies

So our queen lady Macbeth is enjoying queenful lavishing services, rewards to her
cold manipulations, but on one day her mind starts to tumble and anxiety breaks
it definitely. Indelible blood in her tainted hands and endless sleepwalking turn
to unwilling crime confession.

The witches have nothing to do with Lady Macbeth, they never interact with
each other in the play, although they appear in this images. This is because I
have used them as the IdP, and up to now and you should be familiar with them
in that role.

So here starts the flow which ends with Lady Macbeth committing suicide (out
of scene); the SAML single logout profile.

41
Three Auth Protocols and Three Shakespeare Tragedies

Being fed up with the use of life and services, our queen clicks on a logout URL
or action. As there can only be a logout URL per site, the queens request reaches
only one SP and clicks in Log out.

42
Three Auth Protocols and Three Shakespeare Tragedies

The SP which receives the logout action destroys the local user session and sends
to the IdP a SAML LogoutRequest message requesting that the user's session be
logged out.

This message is digitally signed (or integrity preserved by other means


depending on the protocol), base64 encoded, and then transmitted in the URL
using the HTTP Redirect binding.

Again with the digital certificates, this time is the SP the one who signs the
request and the IdP the one who validates it; the other way round as shown in
the final steps of Web SSO profile with the POST binding. Trust flowing both
ways, like blood in Macbeths Scotland.

What does this imply? Both digital certificates (from SP and IdP) must be present
in the metadata when exchanged.

43
Three Auth Protocols and Three Shakespeare Tragedies

The LogoutRequest message, apart from being digitally signed, must contain a
NameID, EncryptedID or BaseID referring the principal as currently recognized
by the identity and service providers prior to this request.

Depending on what OASIS SAML document you find yourself in your clean or
blood stained hands, it could require or recommend the inclusion of the
SessionIndex parameter, so here we will say that is should appear in the
LogoutRequest message. As you have guessed, the parameter carries the users
session internal identifier shared between SP and IdP. Note that this parameter is
extremely helpful in federated scenarios where the NameID field value does not
need to be the same among different SPs.

Additional optional parameters are NorOnOrAfter which specifies a Request


TTL, and Reason which allows a URI string as indication of the logout reason.

44
Three Auth Protocols and Three Shakespeare Tragedies

After processing the request, the IdP must determine other user active session
SPs retrieving this information from the security context. Having determined
that other SPs are also participants in the web SSO session, the IdP sends a
LogoutRequest message to those providers. In this example the request in sent
inside a POST binding, which as you sure know by now, must be digitally
signed.

45
Three Auth Protocols and Three Shakespeare Tragedies

The other SPs (SP2 in this image) replies with a signed LogoutResponse message
to the IdP.

Responses from the other SPs (the not manully logged ut which initiated this
whole profile flow) must be consistent with the request they receive. It has no
sense to reply with a HTTP Redirect binding to a HTTP POST Binding. Yes, I
know, in the first profile SP-Initiated we used an HTTP POST to reply and
AuthnRequest carried by a HTTP Redirect binding, but this POST had an auto-
submit (or it was triggered by a trivial user action) almost looking like the
requesting Redirect binding. What primes here, apart from security, is user
experience. If the IdP issues a POST Binding to a SP not interacting with the final
user, it does not look very sensible to answer with a HTTP Redirect trough the
users browser.

46
Three Auth Protocols and Three Shakespeare Tragedies

The LogoutResponse message must be, as we said before, digitally signed (or
integrity protected by any other means available).

No information or tags of what a LogoutResponse message must carry are


specified in the standard documentation. The illustration here just proposes an
example. A Status tag or StatusCode parameter is highly recommended for
informative purposes.

47
Three Auth Protocols and Three Shakespeare Tragedies

The identity provider returns another LogoutResponse message containing a


suitable status code response to the original requesting service provider, SP1.

The response, as you imagined, is digitally signed.

48
Three Auth Protocols and Three Shakespeare Tragedies

The response is structurally the same as the ones delivered to the other SPs.

49
Three Auth Protocols and Three Shakespeare Tragedies

Finally, the SP1 informs the user that they are logged out of all the providers.

50
Three Auth Protocols and Three Shakespeare Tragedies

This image illustrates the full flow with HTTP redirect bindings to communicate
the first SP with the IdP, and Artifact bindings to communicate the IdP with the
other SPs, as illustrated in the OASIS SAML V2.0 Technical Overview document.

51
Three Auth Protocols and Three Shakespeare Tragedies

So summarizing the example, we have seen the Single Logout profile with front-
channel bindings. Remember that POST Bindings must be digitally signed, or
integrity protected either way, and that the request and response within every
unique SP must be consistent.

And now, after a spiral descent into madness, the queen is dead. Logged out.

What happened with the murderous and now solitary king? Ill tell you.

When hearing about the news of his wifes demise he falls in despair, ruminates
about the brevity of a meaningless life and pronounces the famous Tomorrow,
tomorrow and tomorrow soliloquy.

Whereas, he has armed his royal castle in Dunsinane to withstand a siege from
MacDuff, Duncans sons, and army of Englishmen and the appalling Scottish
noblemen afraid of the blood tainted king.

Only before the battle is about to start does Macbeth see the forest moving, due
to the Englishmen disguising themselves with boughs and tree limbs and
advancing silently towards the castle.

In the middle of the heat of the battle, which culminates with a duel between
Macbeth and Macduff, does the former learn that the latter was born by
Caesarean section and not at least literally from woman, thus fulfilling the

52
Three Auth Protocols and Three Shakespeare Tragedies

prophecies of the witches. Too much for a plot quibble, but not the least twisted in
the Shakespearean plays.

Macbeth is beheaded by Macduff and Malcom, the elder of Duncans sons, is


crowned king. What about the prophecy cast to Banquo? According to the
Holinshed's Chronicles, Banquo (the historical one) was an ancestor of king
James I of England and VI of Scotland, first of the Stuarts, who was ruling
when this tragedy was first premiered.

52
Three Auth Protocols and Three Shakespeare Tragedies

Lets talk a bit about federations. They use the SAML concepts mentioned and
explained before and resemble protocol flows we have dissected during the
tragedy, but federations appear when different (usually multi-domain) web
services want to offer their services together for their respective users.

Before Macbeth is crowned king he is already lord of Inverness castle. Then


becoming king he becomes also lord of Dunsinane castle (apart from the rest of
Scotland), so servants in Dunsinane must acknowledge their new king and serve
him without the king having to travel there and ordering them to (this means,
without signing up or creating a service account in Dunsinane), there must be
other way out of the end user realm to transfer user credentials from
Inverness to Dunsinane. They have to federate the kings account.

Centralized federations provides single points of web application access control


and auditing, which has security, risk and compliance benets. Identity
federation also provides a means for these partner services to agree on and
establish a common, shared syntax and name identifier to refer to the users
(registered in only one of the services) in order to share information about the
user across the service repositories. This way every service does not need to
manage and store credentials for each user in this scenario.

The SAML 2.0 documentary standard recognizes three main federation


establishment schemes plus a federation termination.

53
Three Auth Protocols and Three Shakespeare Tragedies

Federation via Out-of-Band Account Linking

This case is the easiest. Two different web services host accounts for the same
user with the same userID via an undefined out-of-scope, out-of-band synching
(such as directory services synchronization).

Following the indications in the picture, this federation resembles a lot to the
web SSO profile SP-initiated. The user requests a service hosted in one website
and is redirected to the other one (acting in this case as IdP) where he or she is
challenged for credentials. After correctly signing in, the signed response is
redirected to the first SP to get the resource or service initially requested.

54
Three Auth Protocols and Three Shakespeare Tragedies

Federation via Persistent Pseudonym Identifiers

The flow is similar to the previous one (almost Web SSO SP-initiated), but in this
case the user has an active account in a SP but not in the other one. Based on the
NameID tag provided by SAML, the account in the first SP (here acts as IdP) can
be assigned a unique internal ID which is also referred to the ID the user creates
in the second SP when accessing for first time.

Lets see it step by step. First the user requests a service or resource in SP2, where
he has never signed up an account. This SP redirects the user to another SP (SP1)
where the user has an active account. SP1 challenges the user for his or her
credentials, and when correctly signed in, creates a signed SAML Response
message with a unique NameID and/or Identity Attributes, and redirected to
SP2, who offers the user to create a account and federate it with the one in the
previous SP (SP1), or will look for an account with a NameID and/or Identity
Attributes corresponding to the received ones from the SP1/IdP and
acknowledge the already registered and federated user. After this check the
session is created and the service or resource (which is transferred during all the
flow in the well-known RelayState parameter) supplied to the user.

This federation case of use still makes the user to be registered with active
accounts in both SPs, but in this case the accounts do not need to be exactly the
same.

55
Three Auth Protocols and Three Shakespeare Tragedies

Federation via Transient Pseudonym Identifiers

This is where we wanted to arrive. Transient identifiers are used when a user has
an account in a SP (SP1) which will act also as IdP, and this user requests a
service or resource hosted in another SP (SP2) where no account for this user
exists and does not need to be created.

This federation can flow as SP-initiated or IdP-initiated. In this example we will


follow the SP-initiated flow. User goes to SP2 requesting a service or resource,
and is redirected to SP1, which acts also as IdP, and where the user is challenged
for his or her credentials. After correctly authenticating, a signed response is
conveyed to SP2 using the NameID and/or Identity Attributes as a base to
identify the user during the session and to supply the requested service or
resource. The identifiers expire when the sessions finishes, thus requiring all the
flow to be completed from the beginning to access the same resource or service
or another one hosted in the same SP2.

See this scheme advantages from two approaches.


First the obvious delegation of accounts and what it takes; for example SP2
does not need to maintain so many users (or even no one) in its database or
directory.
On the other hand, if correctly implemented (and with a bit of trust), the
SP1/IdP could act as a true anonymizer for services hosted in SP2 by not
transmitting in the Response more information than just the generic lot
required to supply the service (particularly with an IdP-initiated flow with
only Identity Attributes and no identifiers).

56
Three Auth Protocols and Three Shakespeare Tragedies

Federation Termination

The problem with using persistent federated identifiers is that there must be a
way to terminate the federation. This happens when a user deletes his or her
account in a SP which is federated with another one (and maybe another, and
another,), which should by himself also delete the account if it was created in
the way of a Federation via Out-of-Band Account Linking or a Federation via
Persistent Pseudonym Identifiers (the first two examples).

In this case is more usual the use of SOAP Bindings because they can be used in
back channels (not through the users browser), being in this way more
confidential and transparent. If used in front channels, which only should be
done if no other way is possible, these messages should be encrypted (SSL/TLS)
for confidentiality and signed for integrity preservation.

The Terminate request is sent to the identity provider using the


ManageNameIDRequest tag, and the response is sent with the
ManageNameIDResponse. An Issuer element and a digital signature (or
binding-specific integrity protection) are mandatory for both request and
response.

57
Three Auth Protocols and Three Shakespeare Tragedies

To end just a few notes about Security and Privacy, extracted from the SAML
Technical Overview by OASIS.

- Remember that SAML is a text-based protocol that includes no native


encryption. When transporting messages in the front channels which carry
confidential information (credentials even hashed credentials , operation
results, etc.) use channel encryption (SSL/TLS mostly) to keep confidentiality.
- For the same reason as the previous one, SAML messages could be
intercepted and tampered with (for example by a MITM attack scenario). To
avoid, or at least minimize exposure to this threat, use digital signatures in the
messages. Remember that the use of signatures is not a global measure
implemented with a line of configuration for all case uses (as it could be
implementing a Always-on TLS encryption channel), but it requires specific
configuration and specific data (digital certificates) per party (name it per SP,
per client,).
- While not always a requirement, using certificates for authentication between
parties (both ways) is highly recommended (but if a lot of parties are
involved, it may became an administrative hell. True story).

And a few good practices.

- Use of transient identifiers for users who access different federated services is

58
Three Auth Protocols and Three Shakespeare Tragedies

OK if the use case fits this scenario, but if persistent identifiers are created
make the user aware that they do not need to be the same text string, and of
course, neither the same password.
- Although authentication contexts are not discussed in this leaflet, they can be
adjusted to an adequate security level in accordance to the service protected. In
a banking universe it is not the same to protect a global positioning query (read
only) which might only require user+password, than a fund transfer which
should require also a second factor of authentication. Adjust your service
security and dont use the same policy for everything.
- Actions such as federating a service with a user account should require consent
from the same user. How this consent is obtained is out of scope of the SAML
protocol.
- When using the RelayState parameter in IdP-initiated flows, control the
parameter, allow only POST methods and, if possible (and not an
administrative hell) whitelist the landing page urls encoded in RelayState.

58
Three Auth Protocols and Three Shakespeare Tragedies

OAuth is the second security protocol were seeing in this document. In


particular, we are discussing OAuth 2.0 version (RFC 6749), which is not
backwards compatible with the 1.0 version (RFC 5849) and renders this last one
obsolete.

OAuth (2.0 if omitted from now on) allows a third party application or client to
have limited access to an HTTP resource (or HTTP retrievable , usually an API); in
some cases this access is done on behalf of the resource owner (being the
resource placed behind the API). OAuth also aims to establish a scenario where a
trust relationship is not formally settled but is required for a certain amount of
time and for some determined actions, which are delimited by scopes, and
provides mechanisms to create this temporal trust without giving away users
credentials (such as passwords) creating a secured delegated access.

If you are new to OAuth these descriptions can be extremely twisted and
confusing (and I am trying to simplify them to make it easier, believe me), but it
will get better with the examples.

OAuth makes use of HTTP protocol communication to issue temporal access


tokens to protected resources. These tokens address only Authorisation, not
authentication (though some define it as pseudo-authentication, but as it is
pseudo it is not real). For further Authentication features we will see OpenID
Connect later on this document, which is built on top of OAuth and adds a layer
of secure and self-contained authentication.

59
Three Auth Protocols and Three Shakespeare Tragedies

Although OAuth is here shown as a security protocol, there is a tense debate


about how scarcely secure it might be (stirred by some of its creators), relying
only on SSL/TLS for confidentiality and on digital certificates for strong
authentication.

The OAuth logo present in the illustrations in this part has been created by Chris
Messina.

Serve this as an introduction for the protocol and an overture to the tragedy, we
are now to enter the scene of a sunny 16th century Venice.

59
Three Auth Protocols and Three Shakespeare Tragedies

Brabantio is a senator in the prosperous republic of Venice, hes the bearded man
on the right of the painting, and he is terribly worried because his beautiful
daughter has eloped and secretly married with the bearded man on the left. See
the picture, there is no shadow cast over this man on the left, his dark skin is
natural; hes a moor. Suppose your sister or daughter had fled to marry a moor.
If its complicated today, imagine in the 16th century.

But stop there the racism. The moor, Othello is the name, is a general in the
Venetian army, a brave and veteran soldier, man of deep honour and friend of
his friends. If that were not enough, the adventurous marriage between Othello
and Desdemona, Brabantios daughter, bears only true love.

Up to this, it could seem Othello play is closer to one from Disney than from
Shakespeare, what could turn this into a tragedy?

The green-eyed monster; jealousy. Arguably the true protagonist on this play.

Rodrigo, a dissolute Venetian gentleman, is also in love with Desdemona (she is,
after all, the beautiful senators daughter, really the great good catch of Venice)
and he is jealous of Othello for marrying her. Iago, Othellos ensign, is jealous of
Cassio, a captain, for being promoted before him, and for this resented with
Othello. Brabantio is jealous of Othelo, for taking his daughter away from him,
and so on.

60
Three Auth Protocols and Three Shakespeare Tragedies

Iago makes his move creating a strife about the lovers elopement in front of
Brabantio, making him order the Venetian military to go after Othello accusing
him of witchcraft.

When captured, Othello defends himself in front of the senate and the Doge. His
claims seem convincing enough and Desdemona confirms them. The scent of true
romanticism fills the room, but Brabantio distrusts:

Look to her, Moor, if thou hast eyes to see:


She has deceived her father, and may thee

And, by the way, theres war declared in the Mediterranean (16th century,
remember?); the Turks are going to attack Cyprus. Othello parts to war taking
Desdemona with him.

60
Three Auth Protocols and Three Shakespeare Tragedies

By the time the Venetian navy arrives in Cyprus, a storm has obliterated the
Turks ships (who didnt send their fleet to fight the elements). So Othello and
Desdemona prepare themselves to have a nice holyday in Brabantios summer
palace. Lucky storm they thought, but idle soldiers tend to do the green eyed
monsters work and Iago is so filled with jealousy and resentment that no happy
honeymoon is going to take place.

By the third Act of the play, Iago has twisted so much Othellos mind playing
with half truths and unhappy coincidences that he is capable of making him
suspect, disparage and even kill like a swaying marionette. Iago uses Othello,
who still has Desdemonas love and trust, as a smoke screen to fulfil his
treacherous and egocentric ends and to drive Othello to the lowest of human
condition.

And this is how OAuth is intended to work. Not by jealousy or bad feelings, but
by creating a temporal trust relation with an API or application to carry out an
action on behalf of a user. Iago uses Othello to do actions on behalf of himself
taking advantage of Desdemonas trust.

See the beautiful picture illustrating this page. The shady character hidden in the
column should be Iago (some argue that she is Emilia, but for this document
suppose he is and androgynous Iago). In the picture you can see Desdemona
issuing a temporal trust token to Othello (the handkerchief).

61
Three Auth Protocols and Three Shakespeare Tragedies

So lets have a look at the main actors that take place in an OAuth scenario. The
RFC defines the following roles:

- Resource Owner: This is the end user, the one who holds credentials but no
active session for the authorisation server.

- Resource server. Hosts and protects the service or resource which the client
wants to access on behalf (or not, depends on the flow) of the user. Te
resource (or protected resource) is property of the resource owner (as its name
implies). This server understands the access tokens.

- Authorisation server: Issues authorisation tokens and codes. This is the server
authorised to authenticate the resource owner.

- Client: Application which requests the protected service or resource which is


hosted in the Resource server. This request can be done on behalf of the end
user (3 legged flow) or for itself (2 legged flow)

62
Three Auth Protocols and Three Shakespeare Tragedies

The OAuth RFC describes 4 + 1 different flows. We will delve later into the gory
details of each one.

Each flow represents a grant type, which are no more than different methods
to obtain access tokens depending on the kind of client that request access.

Depending on the existence of a end-user or resource owner the flows are called
2 legged or 3 legged. In the 2-L flow the client acts as an end-user with
credentials of its own.

The grant types are classified according to the RFC as follows:

- 3 Legged grants:
- Authorisation Code
- Implicit
- Resource Owner Credentials
- 2 Legged Grants
- Client Credentials
- Refresh token

63
Three Auth Protocols and Three Shakespeare Tragedies

Before going down deep to details lets have a glance to what OAuth offers us.
This is the typical example, which is very similar to the one suggested in the
OAuth official site.

Imagine you have photographs published in an image social network or


repository (Picasa, Instagram, Flickr, choose your own), and you decide you
want to print some of them to use as tapestries in your Cyprus palace you use as
summer residence to commemorate a wedding. As you want to print the images
in photographic quality and king-size bed sheet size, you need a specialised
printing house.

Now suppose you find one of this print houses and, as with all important
decisions in life, you decide to trust them.

They let you choose where do you want to get the pictures from.

64
Three Auth Protocols and Three Shakespeare Tragedies

You choose Picasa (now deceased). To retrieve the pics from the Picasa site, in an
OAuth-less world, the printer site would have no other way than to ask you for
your Picasa credentials (which are Google credentials!), and you would have to
trust them.

65
Three Auth Protocols and Three Shakespeare Tragedies

The printer site would make use of your credentials, log in with them in Picasa
and retrieve the pics. Your google credentials are now also in the printers site
possession. You do not need to be a cybersecurity expert to know this is not
good nor fair.

Passwords and Credentials have a light resemblance to Iagos concept of


reputation:

Reputation is an idle and most false imposition; often got without merit, and lost without
deserving.
(Act II, scene iii)

66
Three Auth Protocols and Three Shakespeare Tragedies

But if you are reading this document you are not so gullible to fall for this
underhanded trick, so you need to know what OAuth offers to you.

Lets start again. In the same scenario you would choose where your pics are
hosted, you (the end user) are choosing the Resource server.

67
Three Auth Protocols and Three Shakespeare Tragedies

You are redirected to the server which is authorised to authenticate the user
whose pics are in the resource server. You have landed in the Authorisation
server.

Note that in this case the Authorisation Server and the Resource Server are both
Picasa.com, but this does not mean that they are the same machine and neither
the same service. Sometimes the Authorisation server and Resource hosting
server are in different domains (But how??? Witchery!!... No.. Remember the multi-
domain federations we saw with Macbeth and SAML 2.0).

Note the importance and subtle difference here, you are login in Picasa/Google
with your google credentials, so no one else than you and google know about
your passwords, they are far and safe from the dishonest trickster bearing the
banner of the printer site.

68
Three Auth Protocols and Three Shakespeare Tragedies

After checking the end user credentials, the authorisation server will show the
user a screen asking for consent of the client performing delimited actions
towards the requested resources.

These limitations to the actions that can be performed are called Scopes, and
they should be as restrictive as possible for the client to carry out the requested
action over the protected resource. If you want only to print photograhs, do not
trust a client when, in this scopes screen, asks for permissions to read your
message inbox.

69
Three Auth Protocols and Three Shakespeare Tragedies

After a correct authentication and scopes are consented, the browser is returned
to the print site with a code in the URL. This is the Authorisation Code (used in
the first of the grant types defined by OAuth RFC), and you will see your
browser screen with a loading message.

Something is happening in the backstage out of scene, but we will see into it
later.

70
Three Auth Protocols and Three Shakespeare Tragedies

And thats it! The printer (client) has retrieved our pics (protected resource)
from picasa (resource server) without knowing the end users password
(resource owners password), because that credentials have only been supplied
to Picasa itself (Authorisation server, Google in this particular case of use).

This course of action is what OAuth offers to us.

Order your tapestries, hang them and let them bear witness to the racism, love,
jealousy, betrayal, revenge and repentance deeds and sins that are to take place
hither in this very palace of Cyprus.

71
Three Auth Protocols and Three Shakespeare Tragedies

But how did the Printer site integrate and access to the end users resources
hosted in Picasa?

With the end-user credentials? No! We said that we were using OAuth to
prevent giving the credentials to the printer.

In fact, the printer has its own credentials to access Picasa, but he cannot directly
access any end users resource with that credentials, he also needs an access
token and a scope to access the photographs.

So, if a client desires to offer resource retrieval services via OAuth the first step is
to fulfil a registration procedure to be able to use the Picasa API.

72
Three Auth Protocols and Three Shakespeare Tragedies

Picasa is the Resource server, for it hosts the photographs.

Google authentication service (as the Picasa Owner) is the Authorisation Server,
for it is the one who asks and checks end users credentials and issues
authorisation codes and access tokens.

The printer site is the client, for it is the app whos going to access a protected
resource hosted in the Resource server with an access token issued by the
Authorisation server.

But wait! We said there were four roles in this OAuth business. Wheres the
fourth? Which ones left?

73
Three Auth Protocols and Three Shakespeare Tragedies

The Resource Owner, who is the end user and is the one who stores resources to
be protected in the Resource server. Thumbs up if you guessed.

Why are not we talking about him now? Because we are discussing the
Registration process, and later the client would be able to offer service via OAuth
to the end users. So, for the moment there are no end users.

74
Three Auth Protocols and Three Shakespeare Tragedies

To carry out the registration process, the client must provide a client type, client
name, client website and Redirect URL or Call-back URL. This last one is the
URL where the service will redirect the user after they authorize (or deny) the
client application scopes. The client type depends on if the client is capable of
storing secrets, this creates two client categories:

- Confidential clients: Capable of keeping its own credentials confidential


(websites hosted in a web server)

- Public clients: Unable to keep its own credential confidential, for example
clients executing on the device used by the resource owner, such as an
installed native application or a web browser-based application where the
code and credentials can be revealed.

This data is filled in usually through a form in the Authorisation server site, but
how this is done figures out of scope of the OAuth RFC.

When submitted and correctly registered it will return a Client_ID and


Client_Secret. The former formally identifies a client and is public information
which may be disclosed to the end-user; the Client_Secret on the other hand,
must be kept secret in the client realm (for confidential clients only) because it
acts like a password.

How should public clients handle client_secrets? Well, they cant, so they should

75
Three Auth Protocols and Three Shakespeare Tragedies

use the Implicit grant type where the secret is not used or the Resource owners
credentials grant type where there is a strong trust relationship between client
and end user.

Optionally, during the registration some other aesthetic data can be submitted
(depending on the Authorisation server), such as client logos, copyright info or
banners to be shown during the Authorisation server request of credentials or
scopes.

Now that you have a perspective over how OAuth works from the point of view
of the end user and the client during the registration, lets see in depth how the
different flows operate.

75
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation Code is the most common and complex of the OAuth flows.
It can only be applied to Confidential clients.

You probably have used it when accessing pages which offer you to log in with
other site credentials; usually log in with Google, log in with Facebook, log
in with LinkedIn,

According to the RFC 6749 Section 1.3.1: The authorization code is obtained by
using an authorization server as an intermediary between the client and resource
owner. Instead of requesting authorization directly from the resource owner, the
client directs the resource owner to an authorization, which in turn directs the
resource owner back to the client with the authorization code. Before directing
the resource owner back to the client with the authorization code, the
authorization server authenticates the resource owner and obtains authorization.
Because the resource owner only authenticates with the authorization server, the
resource owner's credentials are never shared with the client.

A bit confusing you say? Now lets dissect this last paragraph step by step.

76
Three Auth Protocols and Three Shakespeare Tragedies

According to the use case we have shown before, the end user wants the client to
perform an action on his behalf, in this case to retrieve some photographs from
Picasa but it could be anything comprehensively supported by the APIfied
service of the resource server, such as demote a captain the end user is envious
of, or even make the client murder his flamboyant new wife out of overjealousy.

The end user starts the OAuth Authorisation Code flows by requesting to be
authenticated with (and in) Google.

77
Three Auth Protocols and Three Shakespeare Tragedies

The client redirects to the Authorisation server with the following parameters in
the URL (always lower case letters):

response_type: In this grant with the value code


client_id: Client identifier obtained during the registration process.
redirect_uri: This parameter is optional but highly recommended, it is the
URL where the end user will land after the authentication in the authorisation
server is completed.
scope: Space separated list of scopes
state: CSRF token. This parameter is optional but highly recommended. The
value of the CSRF token is stored in the users session to be validated later.

As you can see, I mention here both optional parameters as highly


recommended, The CSRF token explains itself, and the Redirect URI, if not
correctly managed, can turn an OAuth flow into a malicious open redirector. We
will see later some security god practices for OAuth infrstructures, but bear in
mind that posterior OAuth-based protocols (OpenID Connect) mandates the use
of the redirect URI parameter and forces a check with the redirect URI stored
from every registration process of a client.

78
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation server validates the parameters received in the redirection


and challenges the end user to supply credentials. The end user authenticates.

79
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation server presents the Scopes sceen to get consent from the end
user.

Usually this screen is shown only the first time and the Authorisation server
remembers the end users choice regarding this particular client.

80
Three Auth Protocols and Three Shakespeare Tragedies

After consent, the Authorisation server redirects the users browser (HTTP 302)
to the client (to the Redirect_URL) with two parameters in the URL (again, lower
case):

code: The Authorization code (remember the name of this flow?)


state: This value must be compared with the value stored in the users session
to ensure the authorization code obtained is in response to requests made by
this particular client rather than another client application.

81
Three Auth Protocols and Three Shakespeare Tragedies

Now we have the code, half the work is done. The end user receives a loading
message (or whatever similar sentence summoning the virtue of patience).

In the illustration the faded grey indicates a process taking place where the end
users eyes cannot fathom, for this is a Confidential client. This 7.2 is the critical
step where the Client secret is transmitted via a POST Request to the
Authorisation server with the Code, the Client ID and the type of grant.

82
Three Auth Protocols and Three Shakespeare Tragedies

If the data supplied to the Authorisation server is correct, it returns an Access


token to the client and an optional refresh token.

According to the OAuth RFC, the token must be delivered in JSON format with
the response header fields Cache-control:no-store and Pragma:no-cache.

Inside the JSON the parameters should be as follow:


- access token: The string value of the access token.
- token_type: It can take two values:
- bearer: indicates that the access token is directly the string in the access
token parameter. This is the usual type.
- mac: Used to issue a Message Authentication Code (MAC) key
together with the access token that is used to sign certain components
of the HTTP requests. Its format and subparameters are out of scope of
this document and are defined in the paper Hammer-Lahav, E., Ed.,
"HTTP Authentication: MAC Access Authentication", Work in Progress,
February 2012.
- expires_in: Optional parameter, but highly recommended. Lifetime of the
token. If absent it should be the default TTL registered by the Authorisation
server.
- refresh_token: Optional. Used to get new access tokens by the client sending
themvia POST with the client_id, client_secret, grant_type=refresh_token and
scope.
- scope: Optional. The scope requested by the client.

83
Three Auth Protocols and Three Shakespeare Tragedies

Additional fields in the access token are possible depending on the OAuth
implementation. The Illustration covers are the ones appearing in the RFC, which
also indicates that unrecognized parameters in the access token must be ignored
by the client.

83
Three Auth Protocols and Three Shakespeare Tragedies

And finally, issuing a POST request with the access token the resources can be
obtained by the client and shown to the end user in the browser.

84
Three Auth Protocols and Three Shakespeare Tragedies

The second flow defined by Oauth is the Implicit flow. It is very similar to the
Authorisation Code flow, following the same conceptual idea, but it is designed
for Public clients that cannot store secrets because all their code is executed in the
end users environment and the Client_Secret would be compromised. Examples
of this kind of clients are pure Javascript applications, SPI applications or
desktop applications.

As no client secret can be safely stored or transmitted, the client does not ask for
and authorisation code to be exchanged for an access token in the back channel,
but directly asks for the Access token.

Lets see the flow in detail.

85
Three Auth Protocols and Three Shakespeare Tragedies

The first steps are the same as with the Authorisation Code flows. The client
request a service to a resource server and the end user decides to authenticate
himself with credentials in the Authorisation server, so the client redirects the
application to this one with the following parameters which are the same used in
the previous flow except for the response_type:

response_type: This grant uses the value token.


client_id: Client identifier obtained during the registration process.
redirect_uri: This parameter is optional but highly recommended, it is the
URL where the end user will land after the authentication in the authorisation
server is completed.
scope: Space separated list of scopes
state: CSRF token. This parameter is optional but highly recommended. The
value of the CSRF token is stored in the users session to be validated later

86
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation server validates the parameters received and challenges the
end user to supply credentials. The end user authenticates.

87
Three Auth Protocols and Three Shakespeare Tragedies

the Authorisation Server presents the Scopes to get consent from the end user.
As in the Authorisation code flow, usually this screen is shown only the first
time, and the Authorisation server remembers the end users choice regarding
the client.

88
Three Auth Protocols and Three Shakespeare Tragedies

When the scopes are validated the authorisation server issues the Access Token
in JSON format. Note that this Access Token must not issue the Refresh token,
because there is no way to keep it secret and, if compromised, someone could
issue continuously access tokens for his or her deviant evil uses.

Remember the client receives a state parameter that should be checked with the
one sent in the first redirection.

Note that in this flow we have illustrated what seem to be redirections (they are,
indeed) but be aware that some clients lack the ability to perform them as a
HTTP browser does. Such clients will require using other methods for
redirecting the client than a 3xx redirection response; for example, returning an
HTML page or interface that includes a 'continue' button with an action linked to
the redirection URI.

Note that here we have not talked about a JSON containing the Access token. It is
delivered via a "application/x-www-form-urlencoded" format which the client
user agent must follow to extract the access token from a full redirect URI that
the user-agent has retained and pass it to the client application.

89
Three Auth Protocols and Three Shakespeare Tragedies

And with the access token, the desired resource is retrieved from the Resource
server.

90
Three Auth Protocols and Three Shakespeare Tragedies

The Resource Owner credentials grant (also called Password grant) uses the end
users name and password as the authorisation grant to get the Access Token.
The credentials must be entered in the client, so this grant type should only be
used with clients with a strong trust relationship with the end user. Although
trusted, the client should not store credentials other than the access token and
refresh token (unless otherwise desired by the gullible user).

Most internet sites using client apps to access their data work with this grant
type (for example the Spotify mobile app), this way yia have a client app in your
mobile with less features (and so it could be lighter) than a browser which does
not need to store user credentials in case the device is stolen and, by the access
token implementation in OAuth 2.0, the sessions have a predetermined
expiration time. It is recommended for applications moving from HTTP-Basic or
Digest authentication schemes.

Clients using this grant flow can be confidential or public, but most are
considered confidential not because the client_secret could not be extracted by
reverse engineering, but because of the trust. In the example above, the Spotify
app is developed by Spotify themselves and not a third-party, so there is an
assumed trust towards it to retrieve Spotify data.

91
Three Auth Protocols and Three Shakespeare Tragedies

As it couldnt be any different in a flow with this name, The end user starts
providing his or her username and password to the client

92
Three Auth Protocols and Three Shakespeare Tragedies

The client sends a POST request to the Authorisation Server with the following
parameters (in lower case) :

grant_type: for this grant, the value must be password


client_id: the clients ID got during the registration. Only if the client is
confidential, if not this parameter is omitted.
client_secret: clients secret got during the registration. Only if the client is
confidential, if not this parameter is omitted.
scope: the space separated scope permissions.
username: end users username
password: end users password

As you should have guessed, this step is also critically confidential due to the
nature of data being transferred, channel encryption must be present though not
required by the specs.

93
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation server validates the end user credentials and the client
credentials is it was categorised as confidential and, if correct, issues the Access
Token JSON directly to the client.

The OAuth RFC mandates the Authorisation Server, if implementing this grant,
to be protected against brute force attacks. Retry limitations should do the trick
here, though alert rising is a plus.

94
Three Auth Protocols and Three Shakespeare Tragedies

And finally, with the access token in a POST request, the protected resource is
retrieved from the server.

The access token JSON is exactly the same as the used in the authorisation code
grant flow.

As this is the easiest and least secure of all the three 3-legged flows it should be
only used if the previous ones are not available (or a great deal of trusts exists
between user and client).

95
Three Auth Protocols and Three Shakespeare Tragedies

Thought the previous grant was easy and far from complex? Wait to see this one.

Here there is not a end user figure in the flow. It is the application by itself who
authenticates in the authorisation server.

Does this mean that this grant is only used when the client works autonomously
without and end user in front of the screen? Well, not really, it means that the
protected resource does not belong to the end user but to the application; for
example when the Skype VoIP endpoint (the desktop application) finishes a call,
it can retrieve, by itself, statistical data about the call. This data belongs to Skype
and not to the user directly (see the EULA if you dont believe me).

96
Three Auth Protocols and Three Shakespeare Tragedies

Iago is greyed out in this illustrations because we said there is not end-user
intervention here.

The flow begins with the client authenticating itself in the Authorisation Server.
The credentials used are client_ID and client_Secret issue, so the client is always
considered confidential in this grant.

Parameters in this POST request are:


grant_type: for this grant, the value must be client_credentials
client_id: the clients ID got during the registration. Only if the client is
confidential.
client_secret: clients secret got during the registration. Only if the client is
confidential.
scope: the space separated scope permissions.

97
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation Server must authenticate the client. If everything is correct it


issues the JSON Access Token back to the client. There must not be a refresh
token.

The JSON issuing the Access token should be the same as in the Authorisation
Code and User Password grants.

98
Three Auth Protocols and Three Shakespeare Tragedies

And finally the access token is sent with a POST request and the protected
resource is accessed.

99
Three Auth Protocols and Three Shakespeare Tragedies

We started the OAuth performance talking about how Access token act as
temporal delegated permissions in a compartmented environment. As temporal
in their nature, it is not usual, during long sessions, to become expired.

When the authorisation servers issue refresh tokens to clients, which generally
are long-lived tokens, these can be used to get new (fresh) access tokens without
having to be redirected and re-challenged for credentials.

Requesting a resource with an expired access token will result in an Invalid


Token error. Remember that only Authorisation Code and Resource Owner
credential flows allow Refresh tokens to be issued.

This grants works very similarly to the client credentials flow.

100
Three Auth Protocols and Three Shakespeare Tragedies

Again Iago is greyed out in this illustrations. No end-user intervention required.

The flow consists of the client issuing a post request with the following
parameters. If the client is confidential, client authentication in the authorisation
server (Client_ID and client_Secret) is mandatory in confidential clients in this
grant.

Parameters in this POST request are:


grant_type: for this grant, the value must be refresh_token
refresh_token: the refresh token issued to the client
client_id: the clients ID got during the registration.
client_secret: clients secret got during the registration for confidential clients.
scope: the space separated scope permissions. Here this parameter is not
really necessary, but if used it must be the same as the ones related to the
access token or an error is returned; and if it not present, the scopes related to
the access token are automatically assumed. Save bandwidth or keep
consistent, you choose.

101
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation Server must authenticate the client if it is confidential. If


everything is correct it issues the new and fresh JSON Access Token back to the
client.

102
Three Auth Protocols and Three Shakespeare Tragedies

Some security considerations regarding OAuth. When beginning this chapter we


mentioned that there was a notorious debate about the OAuth security, because
it must rely on channel encryption to remain confidential. If you have followed
the flows we have dissected, confidential data is transferred now and then while
the RFC does not speak very openly about encryption, so make it a must; The
channel must be encrypted for credentials, codes and tokens.

Bearer tokens are juicy pies for attackers, specially MITM attackers. In the
Authorisation Code grant type the mac tokens have been mentioned. These are
delivered with a nonce and mac values. If you have been paying attention,
OAuth consists mostly in authenticating the client to the authorisation server,
but never the other way round. Although some grants explicitly impose brute
force protection attacks, it is better to apply MAC messages or at least
Timestamps to client-to-server requests.

CSRF must be taken into account in two different steps. First when the end user
uses the log in with your XxXxXxX Account/Credentials action. Although the
Authorisation server should be protected against CSRF attacks, reality and fast,
careless development deadlines reveals that some of them are not. A CSRF attack
against the authorization server could result in an attacker obtaining end-user
authorization for a malicious client without involving or alerting the end-user;
CSRF login him or her out, CSRF login the attacker with a dummy account and
spoofing the victims authentication to the authorisation server, resulting in the
victim accessing the attackers dummy account resources and the attacker

103
Three Auth Protocols and Three Shakespeare Tragedies

accessing the victims resources. This could be avoided by generating a random


token in the first log in with action to be checked later.

The second step where CSRF may appear in an Authorisation code grant is after
the successful authentication in the authorisation server, issuing the code but
stopping the notification to the client. This use case is symmetric to the previous
one. Later an attacker could force the victim to access a malicious crafted client url
with the code and link the attackers authenticated account with the victims
protected resources. To avoid this second CSRF potential scenario the parameter
state is used in the requests.

The time it should take a token to expire has risen also heated discussion, mostly
the one regarding refresh tokens. Some security analysts advocate to forsake
refresh tokens because of their long expiration time and the triviality for obtaining
access tokens with them. Adjust them to your security requirements. Other
artisans proposing secure versions of OAuth avoid refresh tokens and force a
signature in every request with access token to the resource server to be validated
there. Not a bad idea but still too way forward for developers who still think of
optional=not needed, but I hope we will see this for OAuth 3.0.

The Redirect_URI is a complicated parameter. First because it gives too much


information to an eavesdropper, and second because it could turn the
Authorisation server into an Open redirector if not correctly validated. The
mitigation to this OAuth vulnerability exceds the standard implementation, but it
consists in having a whitelist of Redirect_URI linked to clients and linked to the
grant types allowed for each.This way an XSS in a client wouldn't be able to get
an implicit grant access_token without having any client_secret by simply
swapping a response_type=token parameter.

Another session fixation issue arises when some authorisation server providers
implement a flawed session management (Twitter, cause I doth possess eyes Im
looking at thee). Although you pretend to use and OAuth flow to authenticate
yourself in the Authorisation server and access another resource which can be in
another domain far far away. Sometimes, when entering the credentials in the
Authorisation server, a session is created and stays open while you are redirected
somewhere else. This way your account could be compromised if left the browser
unattended and a malicious attacker sits in your chair while you are using the
bathroom.

103
Three Auth Protocols and Three Shakespeare Tragedies

And what happened to our Moor? And Iago?

Iago thrives in his natural talent to manipulate people to do his bidding, and his
bidding is always full of envy and destructive motives. Manipulates Othello to
be suspicious of Cassio and Desdemona, manipulates Cassio to confess an affair
with Bianca (a local courtesan), manipulates Bianca to despise Cassius,
manipulates Othello to disparage Desdemona, make her life really miserable
He is, far beyond any doubt, champion in using others to do actions on his behalf
and remain hidden, just the same analogy we wanted to follow with OAuth
clients and users credentials.

An then the killings start, and the bloodbath follows. Rodrigo attacks Cassio
(convinced by Iago), Cassio wounds Rodrigo, Iago stabs Cassio, Iago kills
Rodrigo (and convey the guilt to Bianca), Iago kills Emilia, And Othello
strangles to death Desdemona, out of boiling jealousy thinking she has been
cheating him with Cassio. Later, Iagos crimes and manipulation would come to
light confessed by an appalled Emilia. What do you think Othello should have
done with Iago then?

He stabbed the scoundrel without killing him, condemning him to live forever in
pain, and Cassio is ordered to take care of him and punish him with justice.

By the way, in the end Othello looks back to what has happened and how much
has he lost; his wife, his honour, his friends, his trust, And hangs himself. Not

104
Three Auth Protocols and Three Shakespeare Tragedies

because what Iago has taken from him, but for what he himself has taken from
him with his doubts and with his envious and jealous green-eyed monster, the
true main character in the tragedy.

104
Three Auth Protocols and Three Shakespeare Tragedies

The last protocol we are explaining in this leaflet will be OpenID Connect
protocol (at least, until I come up with another Shakespearean security protocol
analogy). OpenID Connect (no version numbers, and abbreviated as OIDC)
derives from OpenID 1.0 and 2.0 and OAuth 2.0 flows.

We saw in OAuth and Othello that one of the main disadvantages regarding the
Access tokens are that they do not carry authentication information, so not until
when bloody murders and attempts start to happen, does the identity of the
behind-the-scenes manipulative Iago come to light, and by then the sweet and
faithful Desdemona is already dead.

To try and solve this problem we shall first travel to the ancient Rome. To the
Ides of March (yes, that Ides of March).

105
Three Auth Protocols and Three Shakespeare Tragedies

The victim in the centre of this painting needs no introduction. Forty Roman
senators, the Libertores, stab Julius Caesar to death soon after he was declared
dictator perpetuo.

As Shakespeares play shows us the character, Caesar is a tenacious violator of


traditional law and ancestral Roman customs, potential tyrant, while an elderly
man dangerously closing to senility and fainting in public. In the play, a deep
moral debate takes place between Cassius and, mostly, Brutus delving into the
ethics of murder in order to avoid not-yet-happened power abuse and how
rightful this preventive murder is.

In the Ides of March, as a soothsayer had predicted, Julius Caesar is murdered in


the Capitol.

What does all this have to do with OpenID Connect? Nothing really, its just an
introduction. Go to the next page.

106
Three Auth Protocols and Three Shakespeare Tragedies

There is an inflection point in the play when the corpse of Julius Caesar is
exhibited in the middle of the forum for burial services. There, Mark Anthony
deftly and eloquently addresses the changeable Roman citizens turning their
opinion against the Libertores. Opposite to Brutus, which is more rational and
logical, Anthonys speech is so manipulative that appeals to primitive emotions
and unleashes a wave of street violence. One of the first populist speeches in
history.

But why does Mark Anthony do this? The naive reader would think of loyalty or
friendship, even revenge; but no, nothing so far from reality. If Caesar is declared
a tyrant, upon his death all designations signed by him in the senate would be
rendered void. Anthony, as well as all Caesars party in the senate, would lose
position and privileges, and government would be led by the opposing party. So
this is the main reason because Anthonys claims about Caesars identity as a
patriot of Rome towards a changeable (sessionless) mob.

This fits OpenID Connect attempts to use self-contained tokens (JSON Web
Token or JWT) which adds self-contained identity information (called claims)
and security features in order to provide a layer of Authentication (transferring
the end users identity) on top of the OAuth authorisation flows allowing access
to RESTful sessionless service architecture or API (which could be seen as the
changeable Roman citizens).

Note that in the left side of the painting you can see a man apparently checking

107
Three Auth Protocols and Three Shakespeare Tragedies

Caesars identity.

107
Three Auth Protocols and Three Shakespeare Tragedies

The JSON Web token is an access token that may contain information other than
the one carried by the Access Token in the OAuth realm. Each of these pieces of
information which state something (usually about the user) is called a Claim. A
JWT is a collection of self-contained claims which are mostly used in OpenID
Connect for Authentication and Identification purposes, though they could also
carry additional information such as the user role or attributes and artifacts as
were discussed in the SAML chapter.

JWT is defined in RFC 7419 and is heavily based on the JWE (JSON Web
Encryption - RFC7516) and JWS (JSON Web Signature - RFC7515) standards. It
is not the objective of this document to dive very deep into them, but some
notions will be given:

The JWT is divided into three sections:


- Header: always contains two parts
- type: Type of token: JWT
- alg: HMAC Hashing algorithm.
- Payload: Where the claims are carried. According to the RFC there can be
three types of claim:
- Reserved: predefined claims which are not mandatory but
recommended:
- iss: Issuer
- sub: Subject
- aud: Audience

108
Three Auth Protocols and Three Shakespeare Tragedies

- exp: Expiration Time


- nbf: Not Before
- iat: Issued At
- jti: JWT ID
- Public: can be defined at will by those using JWTs. Collision resistant
names are recommended.
- Private: custom claims created to share information between parties
that agree on using them.
- Signature: according to the algorithm mentioned in the header. The signature
must be an HMAC calculated as HMAC(base64UrlEncode(header) + "." +
base64UrlEncode(payload), secret)

The token in the wild must have the header and payload base64 encoded and the
signature appended. All three fields should be separated by a period (.).

As JSON is less verbose than XML, when it is encoded its size is also
smaller, making JWT more compact than SAML. This makes JWT a good
choice to be passed in HTML and HTTP environments; the user agent
should send the JWT, typically in the Authorization header using the
Bearer schema.

108
Three Auth Protocols and Three Shakespeare Tragedies

According to the specs, The following Claims are defined to be used within the
ID Token used by OpenID Connect:

iss: REQUIRED. Issuer Identifier for the Issuer of the response. The iss value
is a case sensitive URL using the https scheme that contains scheme, host, and
optionally, port number and path components and no query or fragment
components.

sub: REQUIRED. Subject Identifier. A locally unique and never reassigned


identifier within the Issuer for the End-User, which is intended to be
consumed by the Client. It MUST NOT exceed 255 ASCII characters in length.
The sub value is a case sensitive string.

aud: REQUIRED. Audience(s) that this ID Token is intended for. It MUST


contain the OAuth 2.0 client_ID of the Relying Party as an audience value. It
MAY also contain identifiers for other audiences. In the general case,
the aud value is an array of case sensitive strings. In the common special case
when there is one audience, the aud value MAY be a single case sensitive
string.

exp: REQUIRED. Expiration time on or after which the ID Token MUST NOT
be accepted for processing. The processing of this parameter requires that the
current date/time MUST be before the expiration date/time listed in the
value. Implementers MAY provide for some small leeway, usually no more

109
Three Auth Protocols and Three Shakespeare Tragedies

than a few minutes, to account for clock skew. Its value is a JSON number
representing the number of seconds from 1970-01-01T0:0:0Z as measured in
UTC until the date/time.

iat: REQUIRED. Time at which the JWT was issued. Its value is a JSON number
representing the number of seconds from 1970-01-01T0:0:0Z as measured in
UTC until the date/time.

auth_time: Time when the End-User authentication occurred. Its value is a


JSON number representing the number of seconds from 1970-01-01T0:0:0Z as
measured in UTC until the date/time. When a max_age request is made or
when auth_time is requested as an Essential Claim, then this Claim is
REQUIRED; otherwise, its inclusion is OPTIONAL.

nonce: String value used to associate a Client session with an ID Token, and to
mitigate replay attacks. The value is passed through unmodified from the
Authentication Request to the ID Token. If present in the ID Token, Clients
MUST verify that the nonceClaim Value is equal to the value of the nonce
parameter sent in the Authentication Request. If present in the Authentication
Request, Authorization Servers MUST include a nonce Claim in the ID Token
with the Claim Value being the nonce value sent in the Authentication Request.
Authorization Servers SHOULD perform no other processing on nonce values
used. The nonce value is a case sensitive string.

acr: OPTIONAL. Authentication Context Class Reference. String specifying an


Authentication Context Class Reference value that identifies the Authentication
Context Class that the authentication performed satisfied. The value "0"
indicates the End-User authentication did not meet the requirements
of ISO29115 level 1. Authentication using a long-lived browser cookie, for
instance, is one example where the use of "level 0" is appropriate.
Authentications with level 0 SHOULD NOT be used to authorize access to any
resource of any monetary value. An absolute URI or an RFC6711 registered
name SHOULD be used as the acr value; registered names MUST NOT be used
with a different meaning than that which is registered. Parties using this claim
will need to agree upon the meanings of the values used, which may be
context-specific. The acr value is a case sensitive string.

amr: OPTIONAL. Authentication Methods References. JSON array of strings


that are identifiers for authentication methods used in the authentication. For
instance, values might indicate that both password and OTP authentication
methods were used. The definition of particular values to be used in
the amr Claim is beyond the scope of OpenId Connect specification. Parties
using this claim will need to agree upon the meanings of the values used,
which may be context-specific. The amr value is an array of case sensitive
strings.

azp: OPTIONAL. Authorized party - the party to which the ID Token was

109
Three Auth Protocols and Three Shakespeare Tragedies

issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This
Claim is only needed when the ID Token has a single audience value and that
audience is different than the authorized party. It MAY be included even when
the authorized party is the same as the sole audience. The azp value is a case
sensitive string.

at_hash: OPTIONAL. base64url encoding of the left-most half of the hash of


the octets of the ASCII representation of the access_token value, where the
hash algorithm used is the hash algorithm used in the alg Header Parameter of
the ID Token.

ID Tokens may contain other Claims. Any Claims used that are not understood by
the relying party must be ignored.

ID Tokens must be signed using JWS and optionally both signed and then
encrypted. If the ID Token is encrypted, it must be signed then encrypted, with
the result being a nested JWT. As Encryption may be symmetric or asymmetric,
JWS signature implies a shared secret, in any case it means a way to establish
trust relationships between asserting party and relying party.

109
Three Auth Protocols and Three Shakespeare Tragedies

There are three flows in the standard documentation of OpenID Connect. By the
names you can deduce theyre very similar to OAuth flows with the Hybrid flow
being the exception.

Authorisation Code is used when the client can be authenticated, and when a
code which later will be exchanged by the token is returned to the user agent; the
code, not the token. As in OAuth, it takes to rounds to get the final token which,
in this protocol is issued by an authority called the Token Endpoint.

Implicit flows are used in clients which cannot be authenticated nor keep any
secret, so the final token is revealed to the user agent. Here we are relying on the
token self-sufficient security features. It takes one round to get the final token
issued by an authority called the Authorisation Endpoint

Hybrid flow, which is the one that shouldnt sound familiar up to now, is used
as a combination of both the previous ones. It can be used with clients that can be
authenticated but the token is revealed to the user agent. We will mention later
what uses can be given to this flow.

Lets begin with the Authorisation Code flow.

110
Three Auth Protocols and Three Shakespeare Tragedies

Like we saw in the OAuth 2.0 Authorisation Code flow, the essence in this play
can be summarized as issuing a code to the client which can be exchanged for an
ID token and Access Token while maintaining it secret from the user agent. This
provides the benefit of not exposing any tokens to the User Agent and possibly
to other malicious applications with access to the browser threads.

111
Three Auth Protocols and Three Shakespeare Tragedies

Imagine the User Agent as Caesar (in spirit only), recently murdered and
exhibited in the forum, who is required by Mark Anthony (the client) to be
regarded as a patriot and enter Elysium (the protected resource/service), and for
this he must convince the Roman citizens (The OpenID Connect provider
service).

Among the citizens there are the ones who authorise (the Milites), the ones who
recognize Caesar as tyrant or patriot, the common folk (the Vulgus), and the ones
who manage information about the rest of the people (the Censors). These two
groups match the Authorisation, Token endpoints and Userinfo Endpoints in the
OpenID Connect providers. When speaking about OAuth we only mentioned the
Authorisation server, but in the OpenID Connect Specification it assumed that
this Authorisation Server has at least three roles made available as different
endpoints or URLs.

112
Three Auth Protocols and Three Shakespeare Tragedies

The client creates an Authorisation request and sends it via HTTP GET or POST
methods.

Required parameters in the URL (GET) or in the form (POST) are the following:

response_type Set to code to indicate an authorisation code flow.


scope Used to specify the scope of the requested authorisation in OAuth. The
scope value openid signals a request for OpenID authentication and ID token,
if this value is not present, it is considered a pure OAuth 2.0 flow.
client_id The client identifier of the relying party at the provider. This
identifier is got in the registration process.
redirect_uri The callback URI for the authentication response. As mentioned
in the OAuth security considerations in the previous chapter, thus redirect
value must match a registered value in the provider. As we are using the
Authorisation Code flow, this URI is not required to be HTTPS, but it is
recommended.

The following parameters are optional, and recommended or not according to a


security and privacy perspective:

state Opaque value set by the relying party to maintain state between request
and callback which can be used as a token to mitigate CSRF.
nonce: Random string or number to mitigate replay attacks. This value

113
Three Auth Protocols and Three Shakespeare Tragedies

associates the Client request to the JWT token (if finally issued).
display: Channel to display the authentication and/or consent interface.
Associate the application with only the allowed channels. Possible values are:
page (full web page), popup, touch (tablet or touch interface) and wap (mobile).
prompt: Indicates if the Provider is allowed to ask for end user login, scopes
consent, end users account selection or none. Values are: none (end user must
be already authenticated), login, consent, select_account
max_age: if the end user is already authenticated, this parameter limits the
maximum time since last authentication forcing the provider to re authenticate
the user if the elapsed time is greater.
acr_values: Authentication Context Class Reference values. Used to populate
the acr claim in the jwt, as mentioned in previous pages. Useful when required
second factors of authentication.

The following optional parameters are NOT recommended from a security


perspective:

id_token_hint: using a previous JWT issued by the provider to the relying


party as a hint. Required when parameter prompt=none or a session was
already established in the provider, otherwise an open door for end users
account hijacking.
login_hint: Indicates the authorization server in the provider what to use as
the login field (email, phone number, username,). Dont let the relying party
suggest a login, make the provider demand it.

113
Three Auth Protocols and Three Shakespeare Tragedies

The Authorisation endpoint in the OpenID Connect Provider checks the required
parameters from the request. If there is not a value openid in the scopes list, the
request is treated as a pure OAuth 2.0 and only an Access Token would be
finally issued in the end of the flow. Unrecognized parameters must be ignored
by the Provider.

If the end user is not authenticated, the provider must challenge him or her for
credentials according to the parameters received or according to the default
configuration.

114
Three Auth Protocols and Three Shakespeare Tragedies

The end user provides credentials to the Authorisation server in the provider.

Once validated, the end user must consent the scopes (if required or so indicated
by parameters in the authentication request) for the protected service he or she is
requesting. Scope consent steps are equivalent to the ones asking and receiving
credentials.

As happened with OAuth, the OpenID Connect providers will ask for scopes
consent only the first time and, from then on, remember the end users
decision.

115
Three Auth Protocols and Three Shakespeare Tragedies

When credentials are validated and scopes consented, the Authorisation


endpoint redirects to the Client Redirect_URI parameter received appending as
parameters the authorisation code issued by the provider (asserting party) and
the state (anti-CSRF token) which, if requested, must be validated by the client.

116
Three Auth Protocols and Three Shakespeare Tragedies

Now the client has the authorisation code; next step is to exchange it for an ID
Token and Access Token (and optional Refresh token). This Token request is
directed towards the Token Endpoint in the provider.

The request is carried out by a POST method in a back channel out of reach from
the User agent. In this case we would be again speaking about a confidential
client because it can keep secrets from the browser. If a client is confidential it
must authenticate in the Token endpoint of the OIDC provider with an
Authorisation header as illustrated in the image.

The form in the POST request must contain the following fields:
client_id and client_secret: If it is a confidential client only. This identifier
and secret are got in the registration process. This parameters are transferred
in the Authorization header basic base64 encoded, which implies a trivial
decodification of the secret, and hence the need to keep secrets from the user
agent.
grant_type: Set to authorisation_code, the flow we are using.
code: with the authorisation code we received in the previous step.
redirect_uri The callback URI for the authentication response.

117
Three Auth Protocols and Three Shakespeare Tragedies

The asserting party must check the client credentials and the authorisation code:
if issued to the client_ID, if issued to a clients authentication request and if fresh
(valid and not previously used).

The Redirect_URI parameter must be checked in order to validate it is the same


that came in the initial request. The specs are not clear about what to do if this
parameter does not appear, but to break the flow and return an error is what I
would recommend.

If correct, the token endpoint from the provider and asserting party issues a
JSON to the client containing the access token, refresh token and ID token (in
JWT format). Token type for the OAuth tokens must be bearer.

The JSON must be delivered with the HTTP response headers Cache-
Control:no-store and Pragma:no-cache

118
Three Auth Protocols and Three Shakespeare Tragedies

The client must validate the ID token and optionally the Access Token.

The Access token can be validated if the ID Token JWT contains a claim at_hash.

According to the OpenID Connect specs, the JWT has to be validated in the
following manner:

1. If the ID Token is encrypted, decrypt it using the keys and algorithms that
the Client specified during Registration that the OP was to use to encrypt the
ID Token. If encryption was negotiated with the OP at Registration time and
the ID Token is not encrypted, the relying party SHOULD reject it.
2. The Issuer Identifier for the OpenID Provider (which is typically obtained
during Discovery) MUST exactly match the value of the iss (issuer) Claim.
3. The Client MUST validate that the aud (audience) Claim contains its client_id
value registered at the Issuer identified by the iss (issuer) Claim as an
audience. The aud (audience) Claim MAY contain an array with more than
one element. The ID Token MUST be rejected if the ID Token does not list the
Client as a valid audience, or if it contains additional audiences not trusted
by the Client.
4. If the ID Token contains multiple audiences, the Client SHOULD verify that
an azp Claim is present.
5. If an azp (authorized party) Claim is present, the Client SHOULD verify that
its client_id is the Claim Value.

119
Three Auth Protocols and Three Shakespeare Tragedies

6. If the ID Token is received via direct communication between the Client and
the Token Endpoint (which it is in this flow), the TLS server validation MAY
be used to validate the issuer in place of checking the token signature. The
Client MUST validate the signature of all other ID Tokens according to JWS
RFC using the algorithm specified in the JWT alg Header Parameter. The
Client MUST use the keys provided by the Issuer.
7. The alg value SHOULD be the default of RS256 or the algorithm sent by the
Client in the id_token_signed_response_alg parameter during Registration.
8. If the JWT alg Header Parameter uses a MAC based algorithm such as HS256,
HS384, or HS512, the octets of the UTF-8 representation of the client_secret
corresponding to the client_id contained in the aud (audience) Claim are used
as the key to validate the signature. For MAC based algorithms, the behavior
is unspecified if the aud is multi-valued or if an azp value is present that is
different than the aud value.
9. The current time MUST be before the time represented by the exp Claim.
10. The iat Claim can be used to reject tokens that were issued too far away from
the current time, limiting the amount of time that nonces need to be stored to
prevent attacks. The acceptable range is Client specific.
11. If a nonce value was sent in the Authentication Request, a nonce Claim MUST
be present and its value checked to verify that it is the same value as the one
that was sent in the Authentication Request. The Client SHOULD check the
nonce value for replay attacks. The precise method for detecting replay attacks
is Client specific.
12. If the acr Claim was requested, the Client SHOULD check that the asserted
Claim Value is appropriate. The meaning and processing of acr Claim Values
is out of scope for the OpenID Conect specification.
13. If the auth_time Claim was requested, either through a specific request for
this Claim or by using the max_age parameter, the Client SHOULD check the
auth_time Claim value and request re-authentication if it determines too
much time has elapsed since the last End-User authentication.

119
Three Auth Protocols and Three Shakespeare Tragedies

Optionally, the client could submit the tokens to the provider userinfo endpoint
to retrieve additional user profile information. This userinfo endpoint request
requires always valid tokens.

120
Three Auth Protocols and Three Shakespeare Tragedies

With valid tokens (Access + ID) and the end user profiling in the client the
protected resource can be accessed.

121
Three Auth Protocols and Three Shakespeare Tragedies

In the previous case we discussed a scenario where the client is somehow


capable of storing secrets from the user agent, that were Mark Anthonys secret
intentions to keep his titles and position despite Caesars murder. As the most
seasoned and accomplished speaker in the play, he turns the crowds opinion to
do his bidding and consider Caesar as a fatherland cultural hero and almost a
god (that would come a little later).

But imagine now a client which is unable to keep secrets from the user agent (a
SPI or a pure javascript application). Imagine Brutus, who is in the play the most
honourable among the honourable, the most sincere among the sincere, trying to
explain Caesars murder from a logical and practical perspective. As the honour
demands, he keeps no secrets to his pairs, so he is the start to the implicit flow.

122
Three Auth Protocols and Three Shakespeare Tragedies

We part from the same point as in the previous flow, but in this case we are not
going to use the Token endpoint because we will obtain no code to exchange for
the token. This is how this flow works.

123
Three Auth Protocols and Three Shakespeare Tragedies

Same as the previous flow, the client creates an Authorisation request and sends
it via HTTP GET or POST methods.

Required parameters in the URL (GET) or in the form (POST) are the following:

response_type Set to token and/or id_token to indicate an Implicit flow. There


can be one of these values or both. id_token asks only for an ID JWT token,
token indicates a pure OAuth Access Token only. To get two tokens, both
parameters must exist. As this is an Implicit flow no Refresh token will be
issued.
scope Used to specify the scope of the requested authorisation in OAuth. The
scope value openid signals a request for OpenID authentication and ID token,
if this value is not present, it is considered a pure OAuth 2.0 Implicit flow.
client_id The client identifier of the relying party at the provider. This
identifier is got in the registration process.
redirect_uri The callback URI for the authentication response. As mentioned
in the OAuth security considerations in the previous chapter, thus redirect
value must match a registered value in the provider. As we are using the
Implicit flow, HTTPS is mandatory.
nonce: This one is Required in this flow. Random string or number to mitigate
replay attacks. This value associates the Client request to the JWT token (if
finally issued).

124
Three Auth Protocols and Three Shakespeare Tragedies

Other parameters are optional just like in the Authorisation code flow. The state
parameter (as illustrated here) is highly recommended.

124
Three Auth Protocols and Three Shakespeare Tragedies

The provider must validate the request and make sure that the Redirect_URI
matches the one it has registered for the Client_ID received.

If correct, the provider challenges the user for credentials, validates the and
requests scopes consent. These steps are carried out exactly in the same way as in
the Authentication code flow.

125
Three Auth Protocols and Three Shakespeare Tragedies

And now is when the thing changes. As the client cannot store secrets out from
the user agent, the authorisation endpoint from the provider directly issues the
tokens if the credentials are correct and the scopes are accepted. It is the
Authorisation endpoint itself the issuer of the tokens, not the token endpoint.

The parameters used for this are:


access_token: The OAuth 2.0 access token, present unless the response_type
value in the request was only id_token.
id_token: This parameter is required (if not we would not be talking about
OpenID Connect). Although in the illustration it is about the same length as
the others it is usually much more longer. In this ID token the claims nonce
and at_hash are mandatory for this implicit flow.
token_type: Unless other type specific to the provider and recognizable by the
client, the value is Bearer.
state: Required if present in the request. Clients MUST verify that the value is
equal to avoid CSRF attacks.
expires_in: Token expiration time in seconds sin the response generation. This
parameter is options because it is supposed to be inside the ID token an a
claim.

126
Three Auth Protocols and Three Shakespeare Tragedies

Token validations have to take place in the client exactly in the same way that
were outlined in the Authorisation code flow with the following distinctive
features:

In the ID token, the value of the nonce Claim MUST be checked to verify that it is
the same value as the one that was sent in the Authentication Request.

The access token must be validated (in the same way than the Authorisation
code flow, but now it must).

Not exactly a difference but a recommendation. Implicit flow tokens should have
a lower expiration time than in Authorisation code flow.

127
Three Auth Protocols and Three Shakespeare Tragedies

Optionally, the client could submit the tokens to the provider userinfo endpoint
to retrieve additional user profile information.

The userinfo endpoint request requires always at least a valid ID Token.

128
Three Auth Protocols and Three Shakespeare Tragedies

With valid tokens (or just ID token) and the optional end user profiling in the
client the protected resource can be accessed.

129
Three Auth Protocols and Three Shakespeare Tragedies

And last but not least, the Hybrid flow. Take the features appearing in any of the
previous two flows, shuffle them and the result is the Hybrid flow.

Cassius, another of the Caesars murder perpetrators, is caught by Brutus


receiving money for the regicide. Why has Cassius instigated Caesars murder?
Was he in for the money and personal benefits like Anthony or for the major
patriotic cause like Brutus? Now doubts about his honour are raised, but he will
later command an army with Brutus against Caesars party; Mark Anthony and
Octavius. So what is his drive? Personal or patriotic?

Both. Cassius is our hybrid flow.

The hybrid flow allows requests via front channels (implicit) and back channels
(authorisation code) either way.

This apparently twisted behaviour can be useful for applications supporting both
channels but not at the same time, or to obtain ID tokens from the authorisation
endpoint (implicit) and refresh tokens from the token endpoint (authorisation
code).

And, mostly, this flow is useful because is the only flow understood by some
commercial well-known products (Microsoft, Im looking at you), while the
other flows are Greek to it

130
Three Auth Protocols and Three Shakespeare Tragedies

Cassius: Did Cicero say anything?


Casca: Ay, he spoke Greek.
Cassius: To what effect?
Casca: Nay: but those that understood him smiled at one another, and shook their heads;
but, for mine own part, it was Greek to me.
(Act I, Scene II)

130
Three Auth Protocols and Three Shakespeare Tragedies

Same scenario. As the hybrid flow uses both authorisation code and implicit
features, we bring back to life the Token endpoint.

131
Three Auth Protocols and Three Shakespeare Tragedies

The client creates an Authorisation request in the same way as it would be done
using the Authorisation code flow.

Required parameters in the URL (GET) or in the form (POST) are the same as in
the Authorisation Code flow with the following distinction:

response_type: Set to values depending on the processing flow to be used.


This value may be code id_token, code token or code id_token token.

As we are using features from the Implicit flow too, the nonce parameter is
mandatory here.

132
Three Auth Protocols and Three Shakespeare Tragedies

The provider must validate the request and make sure that the Redirect_URI
matches the one it has registered for the Client_ID received.

If correct, the provider challenges the user for credentials, validates the and
requests scopes consent. These steps are carried out exactly in the same way as in
the Authentication code flow.

133
Three Auth Protocols and Three Shakespeare Tragedies

When credentials are validated and scopes accepted, the Authorisation endpoint
redirects to the Client Redirect_URI parameter received appending as
parameters the same used in the Implicit flow plus the authorisation code.

The parameters used for this are:


access_token: The OAuth 2.0 access token, present if the response_type value in
the request was code token or code id_token token.
id_token: present if the response_type value in the request was code id_token or
code id_token token. In this ID token the claims nonce and at_hash are
mandatory for this hybrid flow (inherited from the Implicit flow).
code: The authorisation code. this value is always present in the Hybrid flow
as well as it would be in an Authorisation code flow.
expires_in: expiration time for the access token. This value is optional.

134
Three Auth Protocols and Three Shakespeare Tragedies

Token validations have to take place in the client exactly in the same way that
were outlined in the Implicit flow with the following distinctive features:

The access token must be validated like in the Implicit flow.

The code must be validated by the client by hashing it with the algorithm
specified in the alg claim from the ID Token header, then the left half of the
resulting hash is base64 encoded and it must match the value in the claim c_hash
from the ID Token. This claim is new and unique to the Hybrid flow.

In the ID token the value of the nonce Claim MUST be checked to verify that it is
the same value as the one that was sent in the Authentication Request. The
claims at_hash and c_hash must be present and used to validate both access
token and authorisation code as mentioned before.

135
Three Auth Protocols and Three Shakespeare Tragedies

If we would want to exchange the authorisation code for another ID Token we


do it in the same fashion as in the Authorisation code This Token request is also
directed towards the Token Endpoint in the provide via POST method in a back
channel.

136
Three Auth Protocols and Three Shakespeare Tragedies

The asserting party must check the client credentials like in the Authorisation
code flow, and issue tokens as requested by the client.

As we are receiving tokens from both the Authorisation endpoint and the token
endpoint there, which is the case for the response_type values code id_token and
code id_token token, the iss and sub Claim Values MUST be identical in both ID
Tokens. The provider MAY be configured to return fewer Claims about the End-
User from the Authorization Endpoint, for instance, for privacy reasons. The
at_hash and c_hash Claims MAY be omitted from the ID Token returned now
from the Token Endpoint even when these Claims are present in the ID Token
returned from the Authorization Endpoint.

The Access token issued here may have the same value or not. Different Access
Tokens might be returned be due to the different security characteristics of the
two endpoints and the lifetimes and the access to resources granted by them
might also be different.

Validation for these last received tokens in the client is performed as in the
Authorisation code flow.

137
Three Auth Protocols and Three Shakespeare Tragedies

Optionally, as in both previous flows, the client could submit the tokens to the
provider userinfo endpoint to retrieve additional user profile information. This
userinfo endpoint request requires always valid tokens.

138
Three Auth Protocols and Three Shakespeare Tragedies

With the corresponding valid tokens (Access + ID), beng those the former or the
later ones, and the end user profiling in the client the protected resource can be
accessed.

139
Three Auth Protocols and Three Shakespeare Tragedies

OpenID Connect addresses some security issues which appeared in OAuth 2.0.
In the specs there is a detailed chapter addressing 21 security attack vectors and
4 privacy disclosure vectors, and each suggesting or assuming a safeguard for
them (most of them inherited from OAuth 2.0 Threat Model and Security
Considerations, RFC 6819).

Although is interesting for some attacks we will here summarize the most
efficient and recommended safeguards which, if correctly implemented, will
thwart all attacks.

- Implement TLS/SSL channels for HTTP traffic.


- As in OAuth flows, we are always talking about authenticating the client and
the end user, and not the server. This server authentication via digital
certificates cloud be interesting in environments prone to server
masquerading.
- Apart from delivering tokens (specially the OAuth Access token) in a
confidential channel (HTTPS) use digital signatures to avoid tampering and
non-repudiation. Digital signatures can be applied in both ways, from client to
server and from server to client, for tokens/responses and requests alike.
- In the tokens, audience, issuer and scopes must be restricted and not free-for-
all, as well as limited in time according to the needs. The issuer value is
recommended to be unique per host. This is more an obvious good practice
than a security safeguard.

140
Three Auth Protocols and Three Shakespeare Tragedies

- Although optional in some flows, using hashes for the items not self-contained
in the JWT inside the token is incommensurably useful.
- Beware of timing attacks. If you implement an OIDC provider from scratch, a
great deal of information can be gathered by trying different tokens and
waiting for a timed response to check is the token was valid or not.
Implementations shouldnt terminate the validation process just when finding
an error but should continue running until all the bytes have been processed to
avoid this attack.

140
Three Auth Protocols and Three Shakespeare Tragedies

Just to end let me tell you what the fate of our noble Brutus was.

Previous to the battle of Philippi, where Brutus and Cassius face Mark Anthony
and Octavius, Caesars ghost appears in front of Brutus announcing his defeat.
He takes the advice, but he thinks that if it is death what he will find let it be.
What did Shakespeare have with ghosts?

Surprisingly Brutus doesnt die that battle, Cassius does by the way, and
committing suicide. So Brutus, the next day shows to battle again knowing that
now he is, far beyond doubt, going to be defeated by Anthony and Octavius
much greater army. When all is lost he also commits suicide by running towards
his sword.

But here comes again another speech from Mark Anthony, the one which closes
the play. In this last speech Anthony addresses that Brutus was the only one true
to his own word, because among all characters involved in the war and murder
he was the only one who did it for personal conviction and for a sense of
rightfulness according to Roman law and traditions, and despite this, Brutus was
the one who has to be laboriously convinced in the first Act. Anthony asserts that
Brutus was really the only true Roman among them.

141
Three Auth Protocols and Three Shakespeare Tragedies

OAUTH
Rohit Ghatol, OAuth 2.0 in Depth (I have taken the liberty to copy some slides
from this great work)
Hardt, D., The OAuth 2.0 Authorization Framework, RFC 6749, October
2012 .
Jones, M. and D. Hardt, The OAuth 2.0 Authorization Framework: Bearer
Token Usage, RFC 6750, October 2012 .
Lodderstedt, T., McGloin, M., and P. Hunt, OAuth 2.0 Threat Model and
Security Considerations, RFC 6819, January 2013.
Jim Manico, OAuth: Where are we going? Nov 2015 OWASP NL Chapter
Meeting.
https://alexbilbie.com/guide-to-oauth-2-grants/
https://www.digitalocean.com/community/tutorials/an-introduction-to-
oauth-2
https://dhavalkapil.com/blogs/Attacking-the-OAuth-Protocol/
Four Attacks on OAuth How to Secure Your OAuth Implementation.
Written by Khash Kiani, SANS Institute.

OPENID CONNECT
https://openid.net/specs/openid-connect-core-1_0.html
http://connect2id.com/learn/openid-connect
https://www.scottbrady91.com/OpenID-Connect/OpenID-Connect-Flows
https://leastprivilege.com/2014/10/10/openid-connect-hybrid-flow-and-
identityserver-v3/

142
Three Auth Protocols and Three Shakespeare Tragedies

de Medeiros, B., Ed., Scurtescu, M., Tarjan, P., and M. Jones, OAuth 2.0
Multiple Response Type Encoding Practices, February 2014
Jones, M., JSON Web Algorithms (JWA), draft-ietf-jose-json-web-algorithms
(work in progress), July 2014.
Jones, M., Rescorla, E., and J. Hildebrand, JSON Web Encryption (JWE),
draft-ietf-jose-json-web-encryption (work in progress), July 2014.
Jones, M., JSON Web Key (JWK), draft-ietf-jose-json-web-key (work in
progress), July 2014.
Jones, M., Bradley, J., and N. Sakimura, JSON Web Signature (JWS), draft-
ietf-jose-json-web-signature (work in progress), July 2014.
Jones, M., Bradley, J., and N. Sakimura, JSON Web Token (JWT), draft-ietf-
oauth-json-web-token (work in progress), July 2014.

SAML
Assertions and Protocols for the OASIS Security Assertion Markup Language
(SAML) V2.0 OASIS Standard 2005.
Profiles for the OASIS Security Assertion Markup Language (SAML) V2.0
OASIS Standard 2005.
Security Assertion Markup Language (SAML) V2.0 Technical Overview
Committee Draft 02, 2008

142
Three Auth Protocols and Three Shakespeare Tragedies

Email: kourcul@protonmail.com
LinkedIn: https://www.linkedin.com/in/koldourkullu/

143

Вам также может понравиться