124

Identity And APIs

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Identity And APIsTechniques to Mature Platform Security

Nordic APIs

copy 2020 Nordic APIs

Contents

Foreword i

Preface iii

PartOneBasic IdentityConcepts1

Introducing The API Security Maturity Model 2

The Difference Between HTTP Auth API Keys and OAuth 12

API Keys ne Security Why API Keys Are Not Enough 22

Why Canrsquot I Just Send JWTsWithout OAuth 29

How To Control User Identity Within Microservices 37

PartTwoOAuthFlowsandDeepDives 47

8 Types of OAuth Flows And Powers 48

Exploring OAuthtools The Worldrsquos First OAuth Play-ground 57

Strategies for integrating OAuth with API Gateways 62

CONTENTS

Assisted Token Flow The Answer to OAuth Integrationin Single Page Applications 71

Using OAuth Device Flow For UI-Incapable Devices 78

SCIM Building the Identity Layer for the Internet 85

Part Three The Role of Identity 93

OAuth 20 ndash Why Itrsquos Vital to IoT Security 94

Is OAuth Enough for Financial-Grade API Security 103

The Role of Identity in API Security 109

Nordic APIs Resources 114

Forewordby Travis Spencer

The other day I rewatched the recording of my first-ever pre-sentation at Nordic APIsrsquo inaugural event in 2013 In that I dis-cussed digital identity and its bearing on APIs I pointed outthat a new stack of security standards had emerged with theadvent ofOAuth OpenIDConnect andSCIM I ran through someflows and specs that I believed would shape API security for thecoming decade and advised listeners to abandon antiquatedpredecessors From my first contribution to this community Ihave sought to explain how important it is to know who is onthe other end of the wire communicating with our APIs

The next day Bill Doerrfeld emailed me a manuscript of thisebook The serendipitous timing struck me in two ways Firstthis central important intersection of digital identity and APIscontinues to be paramount to all practitioners in the space Itis not surprising that 5 out of 10 of the most popular videos ontheNordic APIs YouTube channel are related to API security Thisaspect of APIs is really challenging and almost all deploymentsmust overcome it Secondly we have come very far as a commu-nity From that short 20 minute presentation to this and otherebooks blog posts presentations and workshops flowing outof this community wersquove made tremendous progress that haslifted not only this group but I dare say IT in general

On behalf of myself and Curity we are very pleased to be apart of Nordic APIs and contribute to this critical discussion Ibelieve that digital identity vis-a-vis APIs will continue to be acentral theme in the API space for the coming decade I think thenuances will change slightly and that the standards will evolve

Foreword ii

However what we have today ndash the info covered in this book ndashwill remain the underpinnings and requisite know-how Digginginto this ebook and the topics it addresseswill bewell worth theeffort and rewarded for years to come

I hope you enjoy reading the work of Bill and his team and thatthis ebook deepens your understanding of this key intersectionof identity and APIs

ndash Travis Spencer

CEO CurityCo-Founder Nordic APIs

Prefaceby Bill Doerrfeld

If yoursquore into building with APIs yoursquore probably introducingnew software architecture to bring scalability and efficiencyadvancements But are you introducing new vulnerabilities aswell

Developersoftendonrsquot traditionallybuild fromanexternal-facingviewpoint But in todayrsquos cloud-native world of Bring Your OwnDevice and remote access security is a more paramount issuethan ever even for internal systems ldquoIf we donrsquot take theseconcerns early on they will cause catastrophic problems lateronrdquo warned Keith Casey in a recent Nordic APIs webinar

Continual exploitsdemonstratea lackof securitymaturityacrossthe cloud industry underscoring the need for more securityforethought To combat these prevalent issues many cyberse-curity experts now turn to identity At Nordic APIs events wersquoverepeatedly witnessed speakers stress the importance of identityhandling tomature API platforms at scale As digital ecosystemsevolve so must access management strategies

Authorization and authentication systems have changed signif-icantly for microservices over the past few years From HTTPBasic Auth to API Keys to OAuth 20 Now experts view OAuthScopes and Claims as the most mature form of API securityCentralized trust using Claims is ldquothe place you want to get to inorder tomature your API Securitymodelrdquo says Jacob Ideskog ofCurityWith this approach authorization is uniformand reliableand attack vectors (or room for honest mistakes) are signifi-cantly reduced

Preface iv

In short to plug security gaps software architects must con-sider identity alongside an API strategy So to torchlight theidentity fires wersquove assembled the top relevant Nordic APIsarticles on APIs and Identity

Wersquove organized APIs and Identity into three parts

bull Part One introduces basic concepts related to API securityand identity Familiarize yourself and see where you sit onthe API Security Maturity Model

bull Part Two dives deeper into OAuth flows giving you thetools to see which is best for your scenario See how otheropen identity standards like SCIMmake this all possible

bull Part Three looks at high-risk sectors where API securityneeds the most focus arguing why an identity emphasisis so important in these areas

Wersquove also linked to the original source for each article so youcan review the deeper conversations thatmany of these articlesinspired

So please enjoy APIs and Identity and let us know how we canimprove If you havenrsquot yet consider following Nordic APIs andsigning up to our newsletter for bi-monthly blog updates andevent announcements We also accept blog contributions fromthe community - if interested please visit our Create With Uspage to submit an article

Thank you for reading

ndash Bill Doerrfeld Editor in Chief Nordic APIs

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Contents

Foreword i

Preface iii

PartOneBasic IdentityConcepts1

Introducing The API Security Maturity Model 2

The Difference Between HTTP Auth API Keys and OAuth 12

API Keys ne Security Why API Keys Are Not Enough 22

Why Canrsquot I Just Send JWTsWithout OAuth 29

How To Control User Identity Within Microservices 37

PartTwoOAuthFlowsandDeepDives 47

8 Types of OAuth Flows And Powers 48

Exploring OAuthtools The Worldrsquos First OAuth Play-ground 57

Strategies for integrating OAuth with API Gateways 62

CONTENTS

Assisted Token Flow The Answer to OAuth Integrationin Single Page Applications 71

Using OAuth Device Flow For UI-Incapable Devices 78

SCIM Building the Identity Layer for the Internet 85

Part Three The Role of Identity 93

OAuth 20 ndash Why Itrsquos Vital to IoT Security 94

Is OAuth Enough for Financial-Grade API Security 103

The Role of Identity in API Security 109

Nordic APIs Resources 114

Forewordby Travis Spencer

The other day I rewatched the recording of my first-ever pre-sentation at Nordic APIsrsquo inaugural event in 2013 In that I dis-cussed digital identity and its bearing on APIs I pointed outthat a new stack of security standards had emerged with theadvent ofOAuth OpenIDConnect andSCIM I ran through someflows and specs that I believed would shape API security for thecoming decade and advised listeners to abandon antiquatedpredecessors From my first contribution to this community Ihave sought to explain how important it is to know who is onthe other end of the wire communicating with our APIs

The next day Bill Doerrfeld emailed me a manuscript of thisebook The serendipitous timing struck me in two ways Firstthis central important intersection of digital identity and APIscontinues to be paramount to all practitioners in the space Itis not surprising that 5 out of 10 of the most popular videos ontheNordic APIs YouTube channel are related to API security Thisaspect of APIs is really challenging and almost all deploymentsmust overcome it Secondly we have come very far as a commu-nity From that short 20 minute presentation to this and otherebooks blog posts presentations and workshops flowing outof this community wersquove made tremendous progress that haslifted not only this group but I dare say IT in general

On behalf of myself and Curity we are very pleased to be apart of Nordic APIs and contribute to this critical discussion Ibelieve that digital identity vis-a-vis APIs will continue to be acentral theme in the API space for the coming decade I think thenuances will change slightly and that the standards will evolve

Foreword ii

However what we have today ndash the info covered in this book ndashwill remain the underpinnings and requisite know-how Digginginto this ebook and the topics it addresseswill bewell worth theeffort and rewarded for years to come

I hope you enjoy reading the work of Bill and his team and thatthis ebook deepens your understanding of this key intersectionof identity and APIs

ndash Travis Spencer

CEO CurityCo-Founder Nordic APIs

Prefaceby Bill Doerrfeld

If yoursquore into building with APIs yoursquore probably introducingnew software architecture to bring scalability and efficiencyadvancements But are you introducing new vulnerabilities aswell

Developersoftendonrsquot traditionallybuild fromanexternal-facingviewpoint But in todayrsquos cloud-native world of Bring Your OwnDevice and remote access security is a more paramount issuethan ever even for internal systems ldquoIf we donrsquot take theseconcerns early on they will cause catastrophic problems lateronrdquo warned Keith Casey in a recent Nordic APIs webinar

Continual exploitsdemonstratea lackof securitymaturityacrossthe cloud industry underscoring the need for more securityforethought To combat these prevalent issues many cyberse-curity experts now turn to identity At Nordic APIs events wersquoverepeatedly witnessed speakers stress the importance of identityhandling tomature API platforms at scale As digital ecosystemsevolve so must access management strategies

Authorization and authentication systems have changed signif-icantly for microservices over the past few years From HTTPBasic Auth to API Keys to OAuth 20 Now experts view OAuthScopes and Claims as the most mature form of API securityCentralized trust using Claims is ldquothe place you want to get to inorder tomature your API Securitymodelrdquo says Jacob Ideskog ofCurityWith this approach authorization is uniformand reliableand attack vectors (or room for honest mistakes) are signifi-cantly reduced

Preface iv

In short to plug security gaps software architects must con-sider identity alongside an API strategy So to torchlight theidentity fires wersquove assembled the top relevant Nordic APIsarticles on APIs and Identity

Wersquove organized APIs and Identity into three parts

bull Part One introduces basic concepts related to API securityand identity Familiarize yourself and see where you sit onthe API Security Maturity Model

bull Part Two dives deeper into OAuth flows giving you thetools to see which is best for your scenario See how otheropen identity standards like SCIMmake this all possible

bull Part Three looks at high-risk sectors where API securityneeds the most focus arguing why an identity emphasisis so important in these areas

Wersquove also linked to the original source for each article so youcan review the deeper conversations thatmany of these articlesinspired

So please enjoy APIs and Identity and let us know how we canimprove If you havenrsquot yet consider following Nordic APIs andsigning up to our newsletter for bi-monthly blog updates andevent announcements We also accept blog contributions fromthe community - if interested please visit our Create With Uspage to submit an article

Thank you for reading

ndash Bill Doerrfeld Editor in Chief Nordic APIs

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

CONTENTS

Assisted Token Flow The Answer to OAuth Integrationin Single Page Applications 71

Using OAuth Device Flow For UI-Incapable Devices 78

SCIM Building the Identity Layer for the Internet 85

Part Three The Role of Identity 93

OAuth 20 ndash Why Itrsquos Vital to IoT Security 94

Is OAuth Enough for Financial-Grade API Security 103

The Role of Identity in API Security 109

Nordic APIs Resources 114

Forewordby Travis Spencer

The other day I rewatched the recording of my first-ever pre-sentation at Nordic APIsrsquo inaugural event in 2013 In that I dis-cussed digital identity and its bearing on APIs I pointed outthat a new stack of security standards had emerged with theadvent ofOAuth OpenIDConnect andSCIM I ran through someflows and specs that I believed would shape API security for thecoming decade and advised listeners to abandon antiquatedpredecessors From my first contribution to this community Ihave sought to explain how important it is to know who is onthe other end of the wire communicating with our APIs

The next day Bill Doerrfeld emailed me a manuscript of thisebook The serendipitous timing struck me in two ways Firstthis central important intersection of digital identity and APIscontinues to be paramount to all practitioners in the space Itis not surprising that 5 out of 10 of the most popular videos ontheNordic APIs YouTube channel are related to API security Thisaspect of APIs is really challenging and almost all deploymentsmust overcome it Secondly we have come very far as a commu-nity From that short 20 minute presentation to this and otherebooks blog posts presentations and workshops flowing outof this community wersquove made tremendous progress that haslifted not only this group but I dare say IT in general

On behalf of myself and Curity we are very pleased to be apart of Nordic APIs and contribute to this critical discussion Ibelieve that digital identity vis-a-vis APIs will continue to be acentral theme in the API space for the coming decade I think thenuances will change slightly and that the standards will evolve

Foreword ii

However what we have today ndash the info covered in this book ndashwill remain the underpinnings and requisite know-how Digginginto this ebook and the topics it addresseswill bewell worth theeffort and rewarded for years to come

I hope you enjoy reading the work of Bill and his team and thatthis ebook deepens your understanding of this key intersectionof identity and APIs

ndash Travis Spencer

CEO CurityCo-Founder Nordic APIs

Prefaceby Bill Doerrfeld

If yoursquore into building with APIs yoursquore probably introducingnew software architecture to bring scalability and efficiencyadvancements But are you introducing new vulnerabilities aswell

Developersoftendonrsquot traditionallybuild fromanexternal-facingviewpoint But in todayrsquos cloud-native world of Bring Your OwnDevice and remote access security is a more paramount issuethan ever even for internal systems ldquoIf we donrsquot take theseconcerns early on they will cause catastrophic problems lateronrdquo warned Keith Casey in a recent Nordic APIs webinar

Continual exploitsdemonstratea lackof securitymaturityacrossthe cloud industry underscoring the need for more securityforethought To combat these prevalent issues many cyberse-curity experts now turn to identity At Nordic APIs events wersquoverepeatedly witnessed speakers stress the importance of identityhandling tomature API platforms at scale As digital ecosystemsevolve so must access management strategies

Authorization and authentication systems have changed signif-icantly for microservices over the past few years From HTTPBasic Auth to API Keys to OAuth 20 Now experts view OAuthScopes and Claims as the most mature form of API securityCentralized trust using Claims is ldquothe place you want to get to inorder tomature your API Securitymodelrdquo says Jacob Ideskog ofCurityWith this approach authorization is uniformand reliableand attack vectors (or room for honest mistakes) are signifi-cantly reduced

Preface iv

In short to plug security gaps software architects must con-sider identity alongside an API strategy So to torchlight theidentity fires wersquove assembled the top relevant Nordic APIsarticles on APIs and Identity

Wersquove organized APIs and Identity into three parts

bull Part One introduces basic concepts related to API securityand identity Familiarize yourself and see where you sit onthe API Security Maturity Model

bull Part Two dives deeper into OAuth flows giving you thetools to see which is best for your scenario See how otheropen identity standards like SCIMmake this all possible

bull Part Three looks at high-risk sectors where API securityneeds the most focus arguing why an identity emphasisis so important in these areas

Wersquove also linked to the original source for each article so youcan review the deeper conversations thatmany of these articlesinspired

So please enjoy APIs and Identity and let us know how we canimprove If you havenrsquot yet consider following Nordic APIs andsigning up to our newsletter for bi-monthly blog updates andevent announcements We also accept blog contributions fromthe community - if interested please visit our Create With Uspage to submit an article

Thank you for reading

ndash Bill Doerrfeld Editor in Chief Nordic APIs

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Forewordby Travis Spencer

The other day I rewatched the recording of my first-ever pre-sentation at Nordic APIsrsquo inaugural event in 2013 In that I dis-cussed digital identity and its bearing on APIs I pointed outthat a new stack of security standards had emerged with theadvent ofOAuth OpenIDConnect andSCIM I ran through someflows and specs that I believed would shape API security for thecoming decade and advised listeners to abandon antiquatedpredecessors From my first contribution to this community Ihave sought to explain how important it is to know who is onthe other end of the wire communicating with our APIs

The next day Bill Doerrfeld emailed me a manuscript of thisebook The serendipitous timing struck me in two ways Firstthis central important intersection of digital identity and APIscontinues to be paramount to all practitioners in the space Itis not surprising that 5 out of 10 of the most popular videos ontheNordic APIs YouTube channel are related to API security Thisaspect of APIs is really challenging and almost all deploymentsmust overcome it Secondly we have come very far as a commu-nity From that short 20 minute presentation to this and otherebooks blog posts presentations and workshops flowing outof this community wersquove made tremendous progress that haslifted not only this group but I dare say IT in general

On behalf of myself and Curity we are very pleased to be apart of Nordic APIs and contribute to this critical discussion Ibelieve that digital identity vis-a-vis APIs will continue to be acentral theme in the API space for the coming decade I think thenuances will change slightly and that the standards will evolve

Foreword ii

However what we have today ndash the info covered in this book ndashwill remain the underpinnings and requisite know-how Digginginto this ebook and the topics it addresseswill bewell worth theeffort and rewarded for years to come

I hope you enjoy reading the work of Bill and his team and thatthis ebook deepens your understanding of this key intersectionof identity and APIs

ndash Travis Spencer

CEO CurityCo-Founder Nordic APIs

Prefaceby Bill Doerrfeld

If yoursquore into building with APIs yoursquore probably introducingnew software architecture to bring scalability and efficiencyadvancements But are you introducing new vulnerabilities aswell

Developersoftendonrsquot traditionallybuild fromanexternal-facingviewpoint But in todayrsquos cloud-native world of Bring Your OwnDevice and remote access security is a more paramount issuethan ever even for internal systems ldquoIf we donrsquot take theseconcerns early on they will cause catastrophic problems lateronrdquo warned Keith Casey in a recent Nordic APIs webinar

Continual exploitsdemonstratea lackof securitymaturityacrossthe cloud industry underscoring the need for more securityforethought To combat these prevalent issues many cyberse-curity experts now turn to identity At Nordic APIs events wersquoverepeatedly witnessed speakers stress the importance of identityhandling tomature API platforms at scale As digital ecosystemsevolve so must access management strategies

Authorization and authentication systems have changed signif-icantly for microservices over the past few years From HTTPBasic Auth to API Keys to OAuth 20 Now experts view OAuthScopes and Claims as the most mature form of API securityCentralized trust using Claims is ldquothe place you want to get to inorder tomature your API Securitymodelrdquo says Jacob Ideskog ofCurityWith this approach authorization is uniformand reliableand attack vectors (or room for honest mistakes) are signifi-cantly reduced

Preface iv

In short to plug security gaps software architects must con-sider identity alongside an API strategy So to torchlight theidentity fires wersquove assembled the top relevant Nordic APIsarticles on APIs and Identity

Wersquove organized APIs and Identity into three parts

bull Part One introduces basic concepts related to API securityand identity Familiarize yourself and see where you sit onthe API Security Maturity Model

bull Part Two dives deeper into OAuth flows giving you thetools to see which is best for your scenario See how otheropen identity standards like SCIMmake this all possible

bull Part Three looks at high-risk sectors where API securityneeds the most focus arguing why an identity emphasisis so important in these areas

Wersquove also linked to the original source for each article so youcan review the deeper conversations thatmany of these articlesinspired

So please enjoy APIs and Identity and let us know how we canimprove If you havenrsquot yet consider following Nordic APIs andsigning up to our newsletter for bi-monthly blog updates andevent announcements We also accept blog contributions fromthe community - if interested please visit our Create With Uspage to submit an article

Thank you for reading

ndash Bill Doerrfeld Editor in Chief Nordic APIs

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Foreword ii

However what we have today ndash the info covered in this book ndashwill remain the underpinnings and requisite know-how Digginginto this ebook and the topics it addresseswill bewell worth theeffort and rewarded for years to come

I hope you enjoy reading the work of Bill and his team and thatthis ebook deepens your understanding of this key intersectionof identity and APIs

ndash Travis Spencer

CEO CurityCo-Founder Nordic APIs

Prefaceby Bill Doerrfeld

If yoursquore into building with APIs yoursquore probably introducingnew software architecture to bring scalability and efficiencyadvancements But are you introducing new vulnerabilities aswell

Developersoftendonrsquot traditionallybuild fromanexternal-facingviewpoint But in todayrsquos cloud-native world of Bring Your OwnDevice and remote access security is a more paramount issuethan ever even for internal systems ldquoIf we donrsquot take theseconcerns early on they will cause catastrophic problems lateronrdquo warned Keith Casey in a recent Nordic APIs webinar

Continual exploitsdemonstratea lackof securitymaturityacrossthe cloud industry underscoring the need for more securityforethought To combat these prevalent issues many cyberse-curity experts now turn to identity At Nordic APIs events wersquoverepeatedly witnessed speakers stress the importance of identityhandling tomature API platforms at scale As digital ecosystemsevolve so must access management strategies

Authorization and authentication systems have changed signif-icantly for microservices over the past few years From HTTPBasic Auth to API Keys to OAuth 20 Now experts view OAuthScopes and Claims as the most mature form of API securityCentralized trust using Claims is ldquothe place you want to get to inorder tomature your API Securitymodelrdquo says Jacob Ideskog ofCurityWith this approach authorization is uniformand reliableand attack vectors (or room for honest mistakes) are signifi-cantly reduced

Preface iv

In short to plug security gaps software architects must con-sider identity alongside an API strategy So to torchlight theidentity fires wersquove assembled the top relevant Nordic APIsarticles on APIs and Identity

Wersquove organized APIs and Identity into three parts

bull Part One introduces basic concepts related to API securityand identity Familiarize yourself and see where you sit onthe API Security Maturity Model

bull Part Two dives deeper into OAuth flows giving you thetools to see which is best for your scenario See how otheropen identity standards like SCIMmake this all possible

bull Part Three looks at high-risk sectors where API securityneeds the most focus arguing why an identity emphasisis so important in these areas

Wersquove also linked to the original source for each article so youcan review the deeper conversations thatmany of these articlesinspired

So please enjoy APIs and Identity and let us know how we canimprove If you havenrsquot yet consider following Nordic APIs andsigning up to our newsletter for bi-monthly blog updates andevent announcements We also accept blog contributions fromthe community - if interested please visit our Create With Uspage to submit an article

Thank you for reading

ndash Bill Doerrfeld Editor in Chief Nordic APIs

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Prefaceby Bill Doerrfeld

If yoursquore into building with APIs yoursquore probably introducingnew software architecture to bring scalability and efficiencyadvancements But are you introducing new vulnerabilities aswell

Developersoftendonrsquot traditionallybuild fromanexternal-facingviewpoint But in todayrsquos cloud-native world of Bring Your OwnDevice and remote access security is a more paramount issuethan ever even for internal systems ldquoIf we donrsquot take theseconcerns early on they will cause catastrophic problems lateronrdquo warned Keith Casey in a recent Nordic APIs webinar

Continual exploitsdemonstratea lackof securitymaturityacrossthe cloud industry underscoring the need for more securityforethought To combat these prevalent issues many cyberse-curity experts now turn to identity At Nordic APIs events wersquoverepeatedly witnessed speakers stress the importance of identityhandling tomature API platforms at scale As digital ecosystemsevolve so must access management strategies

Authorization and authentication systems have changed signif-icantly for microservices over the past few years From HTTPBasic Auth to API Keys to OAuth 20 Now experts view OAuthScopes and Claims as the most mature form of API securityCentralized trust using Claims is ldquothe place you want to get to inorder tomature your API Securitymodelrdquo says Jacob Ideskog ofCurityWith this approach authorization is uniformand reliableand attack vectors (or room for honest mistakes) are signifi-cantly reduced

Preface iv

In short to plug security gaps software architects must con-sider identity alongside an API strategy So to torchlight theidentity fires wersquove assembled the top relevant Nordic APIsarticles on APIs and Identity

Wersquove organized APIs and Identity into three parts

bull Part One introduces basic concepts related to API securityand identity Familiarize yourself and see where you sit onthe API Security Maturity Model

bull Part Two dives deeper into OAuth flows giving you thetools to see which is best for your scenario See how otheropen identity standards like SCIMmake this all possible

bull Part Three looks at high-risk sectors where API securityneeds the most focus arguing why an identity emphasisis so important in these areas

Wersquove also linked to the original source for each article so youcan review the deeper conversations thatmany of these articlesinspired

So please enjoy APIs and Identity and let us know how we canimprove If you havenrsquot yet consider following Nordic APIs andsigning up to our newsletter for bi-monthly blog updates andevent announcements We also accept blog contributions fromthe community - if interested please visit our Create With Uspage to submit an article

Thank you for reading

ndash Bill Doerrfeld Editor in Chief Nordic APIs

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Preface iv

In short to plug security gaps software architects must con-sider identity alongside an API strategy So to torchlight theidentity fires wersquove assembled the top relevant Nordic APIsarticles on APIs and Identity

Wersquove organized APIs and Identity into three parts

bull Part One introduces basic concepts related to API securityand identity Familiarize yourself and see where you sit onthe API Security Maturity Model

bull Part Two dives deeper into OAuth flows giving you thetools to see which is best for your scenario See how otheropen identity standards like SCIMmake this all possible

bull Part Three looks at high-risk sectors where API securityneeds the most focus arguing why an identity emphasisis so important in these areas

Wersquove also linked to the original source for each article so youcan review the deeper conversations thatmany of these articlesinspired

So please enjoy APIs and Identity and let us know how we canimprove If you havenrsquot yet consider following Nordic APIs andsigning up to our newsletter for bi-monthly blog updates andevent announcements We also accept blog contributions fromthe community - if interested please visit our Create With Uspage to submit an article

Thank you for reading

ndash Bill Doerrfeld Editor in Chief Nordic APIs

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Part One Basic IdentityConcepts

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Introducing The API SecurityMaturity Modelby Kristopher SandovalOriginally Published Here

Identity ranks high atop the API Security Maturity Model

When a user utilizes a service they must first attest that theyare who they say they are In most use cases they must thenattest that they candowhat theyrsquore trying to do Formanyusersthis is an opaque process that happens magically behind thescenes The reality of implementing this system however hasresulted in an ever-evolving security landscape that requiresspecific modes of authentication and authorization

Thus the question becomes apparent how canwe encapsulateinformation about the user their rights and their origin in auseful way Wouldnrsquot it be great if an API could know who you

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Introducing The API Security Maturity Model 3

are whether to trust you and whether you can do what youclaim to do Thatrsquos the idea behind the API Security MaturityModel Today wersquore going to dive into this model and look atthe fundamental approach to security that if offers

Review Richardson Maturity Model

The API SecurityMaturityModelwas invented by Jacob IdeskogSolution Architect amp Identity Specialist at Curity The idea aroseas a corollary to the Richardson Maturity Model As such beforewe dive into the API Security Maturity Model letrsquos first examineits inspiration

Leonard Richardson created the Richardson Maturity Model toreflect the reality of the RESTful API space In essence itrsquos pos-sible for an API to be REST-like while not being truly RESTfulAccordingly REST compliance is not a duality but rather a seriesof levels of increasing compliance

bull Level 0 The Richardson Model has four levels though thefirst level is considered ldquolevel zerordquo as it reflects absolutelyno REST compliance This level of maturity represents anAPI that doesnrsquot make use of hypermedia URIs often has asingle URI andmethod for calling that URI

bull Level 1 As we get more complicated we enter Level onewhere we start to see the use of multiple URIs with simpleinteractions Key to remember here is that these multipleURIs still have simple verbiage usage

bull Level 2 Level Two is a significant evolution in that it boastsboth multiple URIs and multiple ways of interacting withthat data This level sees far more complex APIs than theprevious levels due to the nature of the verbiage used ndashspecifically CRUD (Create Read Update and Delete) is

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Introducing The API Security Maturity Model 4

usable on exposing resources allowing complex manipu-lation

bull Level 3 The highest level of maturity APIs in this stageare truly ldquoRESTfulrdquo in that they employ Hypermedia as theEngine of Application State (HATEOAS) This results in ahighly complex and powerful API both boasting multipleURIs and the verbiage to interact with them as well as thepower behind hypermedia

The Richardson Maturity Model predecessor to The API Security MaturityModel

The API Security Maturity Model

The interesting thing about the Richardson Maturity Model isthat itrsquos not simply different states of compliance It representscumulative upgrades from level to level with each new stepincluding previous gains and leveraging new additions

Similarly the API Security Maturity Model describes API securityas ever-increasing levels of security complexity and efficiency

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Introducing The API Security Maturity Model 5

The API Security Maturity Model model like the RichardsonModel moves from the lowest-maturity to the highest and canbe considered akin to a playbook for how to progress into asecure platform deployment

With this inmind letrsquos take a look at the specific levels of the APISecurity Maturity Model starting with the lowest maturity levelandmoving towards the highest

Level 0 - API Keys and Basic Authentication

Level 0 is really just the starting point for most security and asa result predictably itrsquos quite basic in nature ndash everything inthe rest of this model quite literally builds on top of the basicauthentication systems and the API keys that interact with themhere Authentication at this level is based upon the notion thatwhoever has the key must have it because itrsquos their key andthus their activity is valid This ldquoauthenticationrdquo is then carried

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Introducing The API Security Maturity Model 6

forward to other endpoints and APIs in a trusted network withthe key data being carried along that path

In essence this type of security is based upon an arguably fun-damentally insecuremethod All an API key does is confirm thatwhoever is holding that key can do what that key allows ndash itdoes nothing to ensure the person who has the key is meantto have it is using it in the proper way or even that they keywas legitimately authorized and is still valid There are alsoadditional concerns in that the user isnrsquot bound to the requestedresource ndash the key could come from almost anywhere as long asitrsquos trusted and that chain of authentication could in theory goanywhere within the network of trust

Therersquos an evenmore serious problemwith this level ofmaturityndash it only provides authentication Authentication just says thatyou are who you say you are (or at the very least you havesomething that says you are who you claim to be) What itdoes not do however is prove that you have the right to makethat claim to access resources that person has rights to accessetc This is authorization which is fundamentally different fromauthentication In order to have authorization we need a morecomplex system

Level 1 - Token-Based Authentication

Token-Based authentication is a more complex system and rep-resents a different level of security maturity Tokens are usedin this case to establish that whoever holds that token is whothey say they are In the wild this is often constructed into asort of quasi-authorization system as the holding of a tokencan be seen as an authentication of both who the person isand what their intent in holding that token is Tokens can bethought of like an identification card It may not necessarily sayyou can do something but due to the fact that you hold thatcard some infer that you are thus trustworthy enough ndash after

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources

Introducing The API Security Maturity Model 7

all you have identified yourself through a securemeans so youmust be trustworthy

A good practical way of thinking about this level of maturityis to frame it in terms of a realistic transport workflow Letrsquossay yoursquore a news publisher You have an inside organizationof writers editors etc who write articles work on reports etcThese authors login to theirworkstations and start pushing theircontent to an application which then presents the content for-ward to the external viewership

In this case you have several tokens working in concert Theauthors are using their tokens to push content forward andattribute that content to themselves The readers likewise havetheir own tokens which allow them to access the applicationand leave comments which are in turn attributed to their pro-file If they are premium subscribers they might even have spe-cial different tokens that allow them different access patternsthrough a quasi-authentication scheme

This level has its own problems of course Authentication To-kens even though they are often used as a sort of authorizationscheme in thewild aremeantonly tobeused forauthenticationBecause of that the quasi-authentication comes from both asuppositionof intent (wow this personhas this token theymustbe trustworthy enough to do this thing) and a complex mix ofconditional statements and fuzzy logic

It should also be noted that using authentication tokens as aform of authorization is often highly insecure due to the natureof how tokens get distributed Machines can get tokens veryeasily ndash and if a machine can do it any malicious actor can doit When tokens are easy to get then your authorization schemedepends almost entirely on a system that is spoofable corrupt-ible and frankly being used for the exact opposite purpose thatwas intended

Introducing The API Security Maturity Model 8

Level 2 - Token-Based Authorization

Token-Based Authorization is a bit like our previous level butthe focus is shifted to authorization At this level wersquore no longeranswering the question of ldquowho are yourdquo but rather ldquowhat canyou dordquo

Oneway to think of this is to imagine a great castle with securedgates In order to enter the castle you can provide your identityndash in other words you can authenticate that you are who yousay you are While that might get you into the gates how doesanyone know you have a right to sell goods To sell goods youmight need a seal from the king that says you are allowed toengage in commerce ndash in other words yoursquod need authorizationthat states youare allowed todo something Your first token saidwho you are and your second token said what you can do

To take our example of authors and readers to another level wecan look at the ability to consume and the ability to publishWhile authentication tokens allowed us to attribute content toa specific user wersquod also need a mechanism to ensure thatonly authors can publish content This is where authorizationcomes in ndash when authors push their content to the applicationfor consumption the system needs to be able to ensure that thecontent came from a trusted source and has been authored bysomeone who has the right to upload the content

This access can be controlled quite granularly using a solu-tion like OAuth ndash implementing scopes can govern permissionsacross a tokenrsquos lifespan and purpose expiry can be set to en-sure that tokens can ldquoage outrdquo of use etc In this way while au-thentication is verymuch a ldquoyes or nordquo proposition (specificallyyou either are who you say you are or yoursquore not) authorizationcan be a much more variable sliding scale of applicability Au-thorization isnrsquot just ldquoyou either can or you canrsquotrdquo it can be ldquoyoucan as long as your token is not expired and it is valid for all thesub-steps within this processrdquo

Introducing The API Security Maturity Model 9

While this might seem like a perfect fix for our security concernsin previous levels there are a few significant reasons that thisis still not enough First and foremost we must ask ourselvesone question ndash who do we trust These systems are designedto be authoritative and as such the token systems that comefrom them must be impervious and trustworthy in order for usto consider their tokens as evidentiary

Additionally we must ask ourselves about how data gets han-dled in transit These tokens get passed forward and as theydo they collect more and more data Accordingly we must askwhatdata isbeingadded andbywhom Ifwecanrsquot know for surethat the data wersquore handling is in fact the same as when it wasissued we lose a significant amount of trust in the data as a corevalue

Level 3 - Centralized Trust Using Claims

Claims are a significant missing piece throughout all of our se-curity layers principally because we are trying to add securityat the wrong place Itrsquos one thing for a user to claim to be whothey are or to claim to have certain rights ndash howdowe trust thatwhat they are saying is true More importantly how do we trustthose who gave the evidence that they are using

Thatrsquos the fundamental question here ndash who do we trust Do wetrust the caller Do we trust the API Gateway How about thetoken issuer Trust secures us but it alsoopensusup topossibleattacks What can we do to fix this

Claims are the fix because they donrsquot simply tell you somethingabout the subject they give you context and the ability to verifythat information There are two core types of attributes that aclaim can reference ndash Context Attributes tell us about the situa-tion when a token is issued and Subject Attributes tell us aboutthe thing that received the token In order to verify this is true

Introducing The API Security Maturity Model 10

we trust an Asserting Party For example letrsquos say we wanted toget a token proving that Nordic APIs has published a post Wecan look to the attributes

1 Attribute

2 publisher Nordic_APIs_Author1

3 publish_Date 1212019

In order to instill better security we can express this informationin a claims token as such

1 Claim

2 Nordic APIs say

3 The publisher is Nordic_APIs_Author1

Using claims we not only say the information we need to saybut we also specify who is attesting that the information is infact true In a practical format the workflow relies quite heavilyon signing and verification When a Requesting Party requestsa token from the Issuing Authority that Authority returns theinformation requested This information is signed using a Pri-vate Key ndash when the Requesting Party wants to verify this infor-mation it can simply using the Public Key to ensure that it wassigned before it was handed off

More to the point encoding and encapsulating data in this wayalso allows us to add each layerrsquos functionality into a singu-lar source with contextualized information While the token isgranted significant trust due to its signed nature the meta con-textual information (and the attestations from the Issuing Au-thority) allows us to know who has requested the informationand what they are allowed to see

Claims also solve the concern of data being added in transit Be-cause the information encoded is signed and controlled by the

Introducing The API Security Maturity Model 11

Issuing Authority nothing is added in transit unless the IssuingAuthority is involved ndash in this way the source of information canbe directly controlled

Conclusion

Security is not a ldquoone size fits allrdquo equation but the fundamentalrequirements of the system are nonetheless quite universalThe need to prove that people are who they say they are andthe need to control access are fundamental concerns for themodernweband the systems that drive it Accordingly choosingthe correct approach for your given security flow is paramountto successful communication

The Difference BetweenHTTP Auth API Keys andOAuthby Daniel LindauOriginally Published Here

OAuth goes beyond basic authentication measures

When designing systems that enable secure authentication andauthorization for API access you must consider how your ap-plications and users should authenticate themselves In thisarticle wersquoll compare three different ways to achieve this APIKeys HTTP Basic Auth and OAuth Wersquoll also highlight what thebenefits and drawbacks are for eachmethod

The Difference Between HTTP Auth API Keys and OAuth 13

API Keys

Using API keys is a way to authenticate an application accessingtheAPIwithout referencinganactual user Theappadds thekeyto each API request and the API can use the key to identify theapplication and authorize the request The key can then be usedtoperformthings like rate limiting statistics andsimilar actions

How the key is sent differs between APIs Some APIs use queryparameters some use the Authorize header some use the bodyparameters and so on For instance Google Cloud accepts theAPI key with a query parameter like this

1 curl -X POST httpslanguagegoogleapiscomv1documents

2 analyzeEntitieskey=API_KEY

Cloudflare requires the API key to be sent in a custom header

1 curl httpsapicloudflarecomclientv4zonescd7d0123e

2 301230df9514d

3 -H Content-Typeapplicationjson

4 -H X-Auth-Key1234567893feefc5f0q5000bfo0c38d90bbeb

5

6 -H X-Auth-Emailexampleexamplecom

API Keys Benefits

Itrsquos relatively easy for clients to use API keys Even though mostproviders use differentmethods adding a key to the API requestis quite simple

API Keys Drawbacks

The API key only identifies the application not the user of theapplication

The Difference Between HTTP Auth API Keys and OAuth 14

Itrsquos often difficult to keep the key a secret For server-to-servercommunication itrsquos possible to hide the key using TLS and re-strict the access to only be used in backend scenarios Howeversincemanyother types of clientswill consume the APIs the keysare likely to leak

Request URLs can end up in logs JavaScript applications havemore or less everything out in the open Mobile apps are easyto decompile and so on Thus developers shouldnrsquot rely on APIkeys formore than identifying the client for statistical purposesFurthermore API keys are also not standardizedmeaning everyAPI has a unique implementation

HTTP Basic Auth

HTTP Basic Auth is a simple method that creates a usernameand password style authentication for HTTP requests This tech-niqueusesaheader calledAuthorizationwithabase64encodedrepresentation of the username and password Depending onthe use case HTTP Basic Auth can authenticate the user of theapplication or the app itself

A request using basic authentication for the user danielwith thepassword password looks like this

1 GET HTTP11

2 Host examplecom

3 Authorization Basic ZGFuaWVsOnBhc3N3b3Jk

Whenusingbasicauthentication foranAPI thisheader isusuallysent in every request The credentials become more or less anAPI key when used as authentication for the application Evenif it represents a username and password itrsquos still just a staticstring

The Difference Between HTTP Auth API Keys and OAuth 15

In theory the password could be changed once in a while butthatrsquos usually not the case As with the API keys these creden-tials could leak to third parties Granted since credentials aresent in aheader they are less likely to endup ina log somewherethan using a query or path parameter as the API key might do

Using basic authentication for authenticating users is usuallynot recommended since sending the user credentials for everyrequest would be considered bad practice If HTTP Basic Auth isonly used for a single request it still requires the application tocollect user credentials The user has nomeans of knowingwhatthe app will use them for and the only way to revoke the accessis to change the password

HTTP Basic Auth Benefits

HTTP Basic Auth is a standardized way to send credentials Theheader always looks the same and the components are easy toimplement Itrsquos easy touseandmightbeadecentauthenticationfor applications in server-to-server environments

HTTP Basic Auth Drawbacks

When a user is authenticated the application is required tocollect thepassword Fromtheuserperspective itrsquos notpossibleto know what the app does with the password The applicationwill gain full access to the account and therersquos no other wayfor the user to revoke the access than to change the passwordPasswords are long-lived tokens and if an attacker would get ahold of a password it will likely go unnoticed When used to au-thenticate the user multi-factor authentication is not possible

The Difference Between HTTP Auth API Keys and OAuth 16

Token-based Authentication Using OAuth20

A token-based architecture relies on the fact that all servicesreceivea tokenasproof that theapplication is allowed to call theservice The token is issued by a third party that can be trustedby both the application and service Currently themost popularprotocol for obtaining these tokens isOAuth 20 specified in RFC6749

OAuth specifies mechanisms where an application can ask auser for access to services on behalf of the user and receive atoken as proof that the user agreed To demonstrate howOAuthworks letrsquos consider the following use case

A user Alice has an account with a service where she can reportthe current indoor temperature of her home Alice also wantsto give a third-party application access to read the temperaturedata to be able to plot the temperatures on a graph and cross-reference with data from other services

The temperature service exposes an API with the temperaturedata so the third party app should be able to access the dataquite easily But how do we make only Alicersquos data available tothe application

Collecting the Credentials

Using Basic authentication the application can collect Alicersquosusername and password for the temperature service and usethose to request the servicersquos data The temperature servicecan then verify the username and password and return therequested data

The Difference Between HTTP Auth API Keys and OAuth 17

However as we noted about there are a few problems with thisapproach

bull The user has to trust the application with the credentialsTheuserhasnomeansof knowingwhat thecredentials areused for

bull The only way for the user to revoke the access is to changethe password

bull The application is not authenticatedbull The scope of access can not be controlled The user hasgiven away full access to the account

bull Two-factor authentication cannot be used

Historically thishascreatedaneed for services todevelopldquoapplication-specific passwordsrdquo ie additional passwords for your accountto be used by applications This removes the need to give awaytheactual password but it usuallymeans giving away full accessto the account On the service provider side you could buildlogic around combining application-specific passwordswith APIkeyswhich could limit access aswell but theywouldbe entirelycustom implementations

The Difference Between HTTP Auth API Keys and OAuth 18

The OAuthWay

Letrsquos look at how we could solve this problem using an OAuth20 strategy To enable better authentication the temperatureservice must publish an Authorization Server (AS) in charge ofissuing the tokens This AS allows third party applications toregister and receive credentials for their application to be ableto request access on behalf of usersTo request access the application can then point the userrsquosbrowser to the AS with parameters like

1 httpsastemperaturescomauthorizeclient_id=third_par

2 ty_graphsampscope=read_temperaturesamphellip

This request will take the user to the AS of the temperature ser-vice where the AS can authenticate Alicewithwhatevermethodis available Since this happens in the browser multiple-factorsarepossible and theonly one seeing thedata is the temperatureservice and the owner of the accountOnce Alice has authenticated the AS can ask if itrsquos ok to allowaccess for the third party In this case the read_temperaturescope was asked for so the AS can prompt a specific question

1 ltbild consentgt

When Alice accepts the client can authenticate itself A token isissued as proof that Alice accepted the delegated access and itis sent back to the third party application

Now the third party application can call the API using the re-ceived token The token is sent alongwith the request by addingit to the Authorization header with the Bearer keyword as fol-lows

The Difference Between HTTP Auth API Keys and OAuth 19

1 GET temperature HTTP11

2 Host apitemperaturescom

3 Authorization Bearer lttokengt

Upon receiving the request the service can validate the tokenand see that Alice allowed the application to read the tem-perature listings from her account and return the data to theapplication

Token Validation

The issued token can be returned in two ways either by return-ing a reference to the token data or returning the value of thetoken directly For the reference token the service will have tosend a request to the AS to validate the token and return thedata associated with it This process is called introspection anda sample response looks like this

The Difference Between HTTP Auth API Keys and OAuth 20

1

2 active true

3 sub ldquoalicerdquo

4 client_id third_party_graphs

5 scope read_temperatures

6 hellip

7

In this response we can see that the user alice has granted theapplication third_party_graphs access to her account with thescope of read_temperatures

Based on this information the service can decide if it shouldallow or deny the request The client_id can also be used forstatistics and rate-limiting of the application Note that we onlygot theusernameof the account in the example but since theASdoes the authentication it can also return additional claims inthis response (things like account type address shoe-size etc)Claims can be anything that can allow the service tomake awellinformed authorization decision

For returning the value a token format like JSON Web Token(JWT) is usually used This token can be signed or encrypted sothat the service can verify the token by simply using the publickey of the trusted AS Tip Read this resource for recommenda-tions on token types

We can see a clear difference here

bull Alice only gave her credentials to the trusted sitebull Multi-factor authentication can be usedbull Alice can revoke access for the app by asking the temper-ature site to withdraw her consent without changing herpassword

bull Alice can allow the third-party app to access only certaininformation from her account

The Difference Between HTTP Auth API Keys and OAuth 21

bull Claims about the user can be delivered to the service di-rectly through the requestNoadditional lookups required

bull The flow is entirely standardized

Summary

Since OAuth 20 was developed in the time of a growing APImarket most of the use cases for API keys and Basic Authen-tication have already been considered within the protocol Itrsquossafe to say that it beats the competition on all accounts Forsmall specific use cases it might be ok to use API keys or BasicAuthentication but anyone building systems that plan to growshould be looking into a token-based architecture such as theNeo Security Architecture

In the use case above I only described the user flow but OAuthof course specifiesalternate flows forobtaining tokens in server-to-server environments You can read more on those in my ear-lier post that explores eight types of OAuth flows and powers

API Keys ne Security Why APIKeys Are Not Enoughby Kristopher SandovalOriginally Published Here

Who holds the key APIs need robust identity control and accessmanagement

Wersquore all accustomed to using usernames and passwords forhundreds of online accounts mdash but if not managed correctlyusing passwords can become a significant distraction and a po-tential security vulnerability The same is true in the API spaceTherersquos nothing inherently wrong with usernames mdash you needthose But if you use them without also having credentials thatallow the service to verify the callerrsquos identity you are certainlydoing it wrong

Unfortunately many API providers make a dangerous mistake

API Keys ne Security Why API Keys Are Not Enough 23

that exposes a large amount of data andmakes an entire ecosys-tem insecure In plain English mdash if yoursquore only using API keysyoumay be doing it wrong

What is an API Key

An API Key is a code assigned to a specific program developeror user that is used whenever that entity calls an API This Key istypically a long string of generated characters which follow a setof generation rules specified by the authority that creates them

1 IP84UTvzJKds1Jomx8gIbTXcEEJSUilGqpxCcmnx

Upon account creation or app registration many API providersassign API keys to their developers allowing them to function ina way similar to an account username and password API keysare unique Because of this many providers have opted to usethese keys as a type of security layer barring entry and furtherrights to anyone unable to provide the key for the service beingrequested

Despite the alluring simplicity and ease of utilizing API Keysin this method the shifting of security responsibility lack ofgranular control andmisunderstanding of the purpose and useamongstmostdevelopersmakesolely relyingonAPIKeysapoordecisionMore than justprotectingAPI keysweneed toprogramrobust identity control andaccessmanagement features to safe-guard the entire API platform

Shifting of Responsibility

In most common implementations of the API Key process thesecurity of the system as awhole depends entirely on the ability

API Keys ne Security Why API Keys Are Not Enough 24

of the developer consumer to protect their API keys and main-tain security However this isnrsquot always stable Take AndrewHoffmanrsquos $2375 Amazon EC2 Mistake that involved a fluke APIkey push to GitHub As developers rely on cloud-based develop-ment tools the accidental or malicious public exposure of APIkeys can be a real concern

From the moment a key is generated it is passed through thenetwork to the user over a connection with limited encryptionand security options Once the user receives the key which inmany common implementations is provided in plain text theuser must then save the key using a password manager writeit down or save it to a file on the desktop Another commonmethod for API Key storage is device storage which takes thegenerated key and saves it to the device on which it was re-quested

When a key is used the API provider must rely on the developerto encrypt their traffic secure their network and uphold thesecurity bargainrsquos side There are many vulnerabilities at stakehere applications that contain keys can be decompiled to ex-tract keys or deobfuscated from on-device storage plaintextfiles can be stolen for unapproved use and passwordmanagersare susceptible to security risks as with any application

Due to its relative simplicity most common implementations ofthe API Keymethodprovide a false sense of security Developersembed the keys in Github pushes utilize them in third-partyAPI calls or even share them between various services eachwith their own security caveats In such a vulnerable situationsecurity is a huge issue but itrsquos one that isnrsquot really brought upwith API Keys because ldquotheyrsquore so simplemdashand the userwill keepthem securerdquo

This is a reckless viewpoint API Keys are only secure when usedwith SSL which isnrsquot even a requirement in the basic imple-mentation of the methodology Other systems such as OAuth

API Keys ne Security Why API Keys Are Not Enough 25

2 Amazon Auth and more require the use of SSL for this veryreason Shifting the responsibility from the service provider tothe developer consumer is also a negligent decision from a UXperspective

Lack of Granular Control

Some people forgive the lack of security After all itrsquos on thedeveloper to make sure solutions like SSL are implementedHowever even if you assure security your issues donrsquot stopthere mdash API Keys by design lacks granular control

Somewhat ironically before API keys were used with RESTfulservices we had WS-Security tokens for SOAP services that letus perform many things with more fine-grained control Whileother solutions can be scoped audienced controlled andman-aged down to the smallest ofminutia API Keysmore often thannot only provide access until revoked They canrsquot be dynami-cally controlled

Thatrsquos not to say API Keys lack any control mdash relatively usefulreadwritereadwrite control is definitely possible in an API Keyapplication However the needs of the average API developeroften warrant more full-fledged options

This is not a localized issue either Asmore andmore devices areintegrated into the Internet of Things this control will becomemore important than ever before magnifying the choices madein the early stages of development to gargantuan proportionslater on in the API Lifecycle

API Keys ne Security Why API Keys Are Not Enough 26

Square Peg in a Round Hole

All of this comes down to a single fact API Keys were nevermeant to beused as a security feature Most developers utilizeAPI Keys as amethod of authentication or authorization but theAPI Key was only ever meant to serve as identification

API Keys are best for two things identification and analyt-ics While analytic tracking can make or break a system othersolutions implement this feature in a more feature-rich wayLikewise while API Keys do a great job identifying a user otheralternatives such as public key encryption HoK Tokens etc doa much better job of it while providing more security

The Pros of API Keys

There are definitely some valid reasons for using API Keys Firstand foremost API Keys are simple The use of a single identifieris simple and for someusecases thebest solution For instanceif an API is limited specifically in functionality where ldquoreadrdquo isthe only possible command an API Key can be an adequatesolution Without the need to edit modify or delete security isa lower concern

Secondly API Keys can help reduce the entropy-related issueswithin an authenticated service Entropy mdash the amount of en-ergy or potential within a system constantly expended duringits use mdash dictates that there are a limited amount of authenti-cation pairs Suppose entropy dictates that you can only have65 million unique pairs when limited within a certain charac-ter set and style In that case you can only have 65 milliondevices users or accounts before you run into an issue withnaming Conversely establishing an API Keywith a high number

API Keys ne Security Why API Keys Are Not Enough 27

of acceptable variables largely solves this increasing theoreticalentropy to a much higher level

Finally autonomy within an API Key system is extremely highBecause an API Key is independent of a naming server andmaster credentials it can be autonomously created While thiscomes with the caveat of possible Denial of Service attacks theautonomy created is wonderful for systems that are designed toharness it

When developing an API a principle of least privilege shouldbe adhered to mdash allow only those who require resources toaccess those specific resources This principle hinges on theconcept of CIA in system security mdash Confidentiality Integrityand Availability If your API does not deal with confidential infor-mation (for instance an API that serves stock exchange tickers)does not serve private or mission-critical information (such asa newsRSS API) or does not demand constant availability (inother words can function intermittently) then API Keys may besufficient

Additionally API Keys are a good choice for developer-specificAPI uses When developers are configuring API clients at oper-ation time and use changing keys for different services this isacceptable

Back to Reality

The benefits of using API Keys outlined above are still tenuousin the general use-case scenario While API keys are simple thelimitation of ldquoread-onlyrdquo is hampering rather than liberatingEven though they provide higher levels of entropy this solutionis not limited to API Keys and is inherent in other authenti-cationauthorization solutions Likewise autonomy can be putin place through innovative server management and modern

API Keys ne Security Why API Keys Are Not Enough 28

delegation systems

Conclusion API Keys Are Not a CompleteSolution

The huge problems with API Keys come when end users notdevelopers start making API calls with these Keys which moreoften than not expose your API to security and managementrisks It comes down to that API Keys are by nature not acomplete solution While they may be perfectly fine for read-only purposes they are too weak a solution to match the com-plexity of a high-use API system Whenever you start integratingother functionality such as writing modification deletion andmore you necessarily enter the realm of Identification Authen-tication and Authorization

Basic API Key implementation doesnrsquot support authenticationwithout additional code or services It doesnrsquot support authen-tication without a matching third-party system or secondaryapplication It doesnrsquot support authorization without some se-rious ldquohacksrdquo to extend use beyond what they were originallyintended for

While an argument could be made for expanding out the APIKeys method to better support these solutions that argumentwould advocate re-inventing the wheel There are already somany improved solutions available that adding functionality toanAPIKey systemdoesnrsquotmakesense Even if youdidaddsome-thing like authentication especially federated authenticationto the system using Shibboleth OpenID etc there are a ton ofsystems out there that already have support for this

Why Canrsquot I Just Send JWTsWithout OAuthby Kristopher SandovalOriginally Published Here

JWTs are only part of the greater API security puzzle

AJSONWebTokenor JWT is anextremelypowerful standard Itrsquosa signed JSON object a compact token format often exchangedin HTTP headers to encrypt web communications

Because of its power JWTs can be found driving some of thelargest modern API implementations For many the JWT repre-sents a great solution that balances weight with efficiency andas such itrsquos often a very attractive standard to adopt for APIsecurity

However a JWT should not be viewed as a complete solutionUnfortunately it seems that there are some significant misun-

Why Canrsquot I Just Send JWTs Without OAuth 30

derstandings as to what a JWT is and how exactly it functionsIn many situations depending on JWTs alone can be extremelydangerous

One of the most common questions about using JWTs is Whycanrsquot I send JWTs without OAuth In this chapter we answerthat very question Wersquoll define what a JWT actually is how itfunctions and why adopting it in isolation is dangerous

What is a JWT

Beforewe addresswhy utilizing JWTs alone is insecure wemustdefine what a JWT actually is JWTs are often conflated with theadditional protocols and systems surrounding them meaningthat the JWT design concept has been bolstered beyond theactual definition of the object itself

JWT is an open standard defined by RFC 7519 The JWT is con-sidered by its authors to be a ldquocompact and self-contained wayfor securely transmitting informationbetweenparties as a JSONobjectrdquo The JWT itself is composed of a Header a Payloadand a signature that proves the integrity of the message to thereceiving server

Why Canrsquot I Just Send JWTs Without OAuth 31

Content encoded inside a JWT is digitally signed either usinga secret utilizing the HMAC algorithm or leveraging the PublicKey Infrastructure (PKI) model with a privatepublic RSA con-figuration While this does lend a certain amount of integrityprotection it does not specifically guarantee security mdash we willdiscuss this at greater length in just a moment but it shouldbe understood that a JWT is an encoding format and only anencoding format

JWTs are loved because they are small and lend themselves toefficient transport as part of a URL as part of the POST parame-ter or even within the HTTP header More lightweight transport

Why Canrsquot I Just Send JWTs Without OAuth 32

options exist and further extensions of the concept exist CWTis a great example utilizing CBOR or Concise Binary ObjectRepresentation to even further reduce the size of the packageand improve efficiency

Themain benefit (and perhaps themain drawback from a secu-rity standpoint) of the JWT standard is that the encoded pack-age is self-contained The JWT package contains everything thesystemwould need to know about the user and as such can bedelivered as a singular object

The Dangers of a Lone Solution

JWTs are powerful mdash therersquos simply no denying that Unfortu-natelymanydevelopers seemto think that theJWT ismore thanan encoding methodology but a complete and secure imple-mentation This is often because JWTs are typically paired witha proper protocol and encryption standard in thewildmdashbut thisis a conscious choice not the result of an automatic security dueto the structure of the JWT itself

A JWT is only secure when itrsquos used in tandem with encryptionand transport security methodologies JWT is a great encodingmethodology but itrsquos not a holistic security measure Withoutadditional protocols backing it up a JWT is nothing more thanan admittedly lightweight and slightly more secure API key

For an example of this insecurity letrsquos look at a common usecase A web API serves as the backend to a web application andwhen the user generates a JWT it is stored as an HTML5 datastorage element This is done so as to aid in the utilization of theAPI over multiple gateways and functions

In this common situation the issue is that the JWT is essentiallyexposed for common use The JWT is digitally signed whichassures a certain amount of guaranteed integrity The server

Why Canrsquot I Just Send JWTs Without OAuth 33

itself is also set to reject any JWT with a manipulated HeaderPayload or Signature component and as such can reject amodified JWT token That being said the token doesnrsquot need tobe modified in order to breach security In theory an attackercould take that token and use it in a sort of replay attack gettingresources that they do not have the authorization to have

While this type of attack can be somewhat mitigated throughthe use of expiration dates this does nothing for man-in-the-middle attacks In the MITM attack scheme the expiration doesnot matter as the attack is initiated live as a middleman

These issues all arise from the simple fact that JWTs are amech-anism for transferring data mdash not for securing it

Securing JWTs

JWTsare self-containedsolutionscontainingeverything theserverneeds to know about who the user is what they need andwhattheyrsquore authorized to do Accordingly theyrsquore great for statelessauthentication and work well with such methods geared forstateless environments

While there are anumber of thirdparty solutions and implemen-tations of stateless authentication the fact is that what yoursquodessentially be creating is a bearer tokenor alternately an accesstoken

Thatrsquos ok and in factwhatwewant todobut this raisesa simplequestion mdash if we are indeed creating such a bearer token whynot use the built-in functionality of the OAuth schema designedspecifically to work with JWTs Therersquos already a great deal ofbuilt-in security functionality in the OAuth specification thatrsquosspecifically engineered to support the JWT so using externalsolutionsmdash often the second question after why canrsquot I just sentJWTs without OAuth mdash is somewhat nonsensical

Why Canrsquot I Just Send JWTs Without OAuth 34

If we utilize the OAuth 20 Bearer Token Usage standard un-der RFC 6750 which incorporates authorization headers wecan essentially create JWTs that would be recognized and spe-cially treated by a wide variety of devices from HTTP proxiesto servers We would thereby reduce data leakage unintendedstorage of requests (as displayed above) and enable transportover something as simple as HTTPS

Proper JWT Utilization

While itrsquos important to secure your JWTs itrsquos also importantto state what the proper utilization of a JWT within the OAuthschema would look like While a JWT can serve many functionsletrsquos take a look at a common use case in the form of the accesstoken Both OAuth 20 and OpenID Connect are vague on thetype of access_token allowing for a wide range of functions andformats That being said the utilization of a JWT as that token isquite ubiquitous for the benefits in efficiency and size alreadynoted

An access token is in simple terms is a token that is used bythe API to make requests on behalf of the user who requestedthe token It is part of the fundamental authorization mecha-nismwithinOAuth and as such confidentiality and integrity areextremely important In order to generate an access token anauthorization code is required All of the elements of this codeare also extremely important to keep confidential and secure

Accordingly a JWT fits this role almost perfectly Because ofthe aforementioned standards that allow for transmission overHTTPS the JWT can contain all of the information needed togenerate the access token Once the token is generated it canlikewise be kept in JWT form as what is called a self-encodedaccess token

Why Canrsquot I Just Send JWTs Without OAuth 35

The key benefit of handling the encoding of the access token inthis way in the OAuth 20 schema is that applications donrsquot havetounderstandyouraccess tokenschemamdashall of the informationis encodedwithin the token itself meaning that the schema canchange fundamentallywithout requiring the clients tobeawareor even affected by such changes

Additionally the JWT is great for this application because of thewide rangeof libraries that offer functionality suchas expirationA good example of this would be the Firebase PHP-JWT librarywhich offers such expiration functionality

Caveats

Ofcourse aswithanysecurity implementation therearecaveatsto consider In the case of the JWT as a self-encoded authoriza-tion solution replay attacks should be considered While adopt-ing proper encryption methodologies should negate many ofthose issues the fact is that the issue is still fundamental tothe concept as a whole and should probably be addressed asa possibility rather than an impossible threat

Accordingly caching the authorization code for the lifetime ofthe code is the suggested solution from OAuth itself By doingthis code can be verified against the known cached code forvalidity and integrity and once the expiration date is reachedautomatically rejected for date reasons

It should also be noted that due to the nature of the JWT oncean authorization code is issued the JWT is self-contained mdash assuch it cannot technically be invalidated at least in its mostbasic configuration The JWT is designed to not hit the databasefor every verification andwhen using a global secret the JWT isvalid until expiration

There are a fewwaysaround this suchas addinga counter in the

Why Canrsquot I Just Send JWTs Without OAuth 36

JWT that increments upon certain events (such as role changeuserdatachange etc) This of course results indatabasepollingfor each request but the amount of data being checked is mi-nuscule enough to make any processing increase somewhatnegligible

Additionally at least in theory you could use sections for spe-cific functions domains and scopes and change that secretwhen a breach is discovered While this would affect more usersthan admins would like it does have the effect of institutingrevocation

That being said proper utilization of the JWT should make thislargely a non-issue as the user still has to provide a certainamount of secret information over an encrypted channel andas such should already be ldquovettedrdquo or controlled

Donrsquot Leave JWT All Alone

The simple fact is that JWTs are a great solution especiallywhenused in tandemwith something likeOAuth Thosebenefitsquickly disappear when used alone and in many cases canresult in worse overall security

That being said adopting the proper solutions can mitigatemany of these threats resulting in a more secure efficient sys-tem The first step to securing your JWT is to understand whatitrsquos not mdash a JWT is an encoding method not an encryptionor transport security method and as such is only part of thepuzzle

How To Control User IdentityWithin Microservicesby Bill DoerrfeldOriginally Published Here

OAuth is necessary to delegate identity throughout a platform

Many developers are well along in their microservices journeys

How To Control User Identity Within Microservices 38

Yet as the number of services increases so do operational is-sues One especially tricky feat is maintaining identity and ac-cess management throughout a sea of independent services

Unlike a traditional monolithic structure with a single securityportal microservices posemany problems Should each servicehave its own independent security firewall How should identitybedistributedbetweenmicroservices and throughoutmy entiresystem What is the most efficient method for the exchange ofuser data

Smart techniques leverage standardized technologies to notonly authorize but perform Delegation across your entire sys-tem This chapter will identify how to implement OAuth andOpenID Connect flows using JSON Web Tokens Wersquoll explainhow to create a distributed authentication mechanism for mi-croservices mdash a process of managing identity where everythingis self-contained standardized secure and best of all mdash easy toreplicate

What Are Microservices Again

Microservicesarchitecture

The microservice design pattern is a way toarchitect web service suites into independentspecialized components These componentsare made to satisfy a very targeted functionand are fully independent deployed as sep-arate environments The ability to recompileindividual units means that development and

scaling are vastly easier within a microservices system

Microservices architecture is opposed to the traditional mono-lithic approach that consolidates all web components into a sin-gle system The downside of a monolithic design is that version

How To Control User Identity Within Microservices 39

control cycles arearduous andscalability is slowTheentire sys-temmust be deployed as one unit since itrsquos packaged together

Monolithic de-sign

The move toward microservices has had dra-matic repercussions across the tech industryallowing SaaS organizations to deploy manysmall services no longer dependent on exten-sive system overhauls Microservices arguablyeasedevelopment andon theuser-facing sideallow accessible pick-and-choose portals to

personalize services to individual needs

Great So Whatrsquos The Problem

Wersquore facedwith theproblemthatmicroservicesdonrsquot lend them-selves to the traditionalmodeof identity control In amonolithicsystem security works simply as follows

1 Figure out who the caller is2 Pass on credentials to other components when called3 Store user information in a data repository

Since components are conjoinedwithin this structure theymayshare a single security firewall They also share the userrsquos stateas they receive it and may share access to the same user datarepository

If the same techniquewere to be applied to individualmicroser-vices it would be grossly inefficient Having an independentsecurity barrier mdash or request handler mdash for each service to au-thenticate identity is unnecessary This would involve callingan Authentication Service to populate the object to handle therequest and respond in every single instance

How To Control User Identity Within Microservices 40

The Solution OAuth As A DelegationProtocol

There is a method that allows one to combine isolated deploy-ment benefits with the ease of federated identity Jacob Ideskogof Curity believes that to accomplish this OAuth should be inter-preted not as Authentication and not as Authorization but asDelegation

In the real world Delegation is where you delegate someone todo something for you In theweb realm the underlyingmessageis there yet it also means having the ability to offer accept ordeny data exchange Treating OAuth as a Delegation protocolcan assist in the creation of scalable microservices or APIs

To understand this process wersquoll first layout a standard OAuthflow for a simple use case Assume we need to access a userrsquosemail account for a simple app that organizes a userrsquos email mdashperhaps to send SMS messages as notifications OAuth has thefollowing four main actors

bull Resource Owner (RO) the userbull Client the web or mobile appbull Authorization Service (AS) OAuth 20 serverbull Resource Server (RS) where the actual service is stored

A Simplified Example of an OAuth 20Flow

In our situation the app (the Client) needs to access the emailaccount (the Resource Server) to collect emails before organiz-ing them to create the notification system In a simplified OAuthflow an approval process would be as follows

How To Control User Identity Within Microservices 41

1 The Client requests access to the Resource Server by call-ing the Authorization Server

2 The Authorization Server redirects to allow the user toauthenticatewhich is usually performedwithin a browserThis is essentially signing into an authorization server notthe app

3 The Authorization Server then validates the user creden-tials and provides an Access Token to Client which can beused to call the Resource Server

4 The Client then sends the Token to the Resource Server5 The Resource Server asks the Authorization Server if the

Token is valid6 The Authorization Server validates the Token returning

relevant information to the Resource Server (ie time tilltoken expiration who the Token belongs too)

7 The Resource Server then provides data to the Client Inour case the requested emails are unbarred and deliveredto the Client

A vital factor tonotewithin this flow is that theClientmdashouremailnotification app mdash knows nothing about the user at this stageThe Token that was sent to the Client was completely opaquemdash only a string of random characters Though this is a secureexchange the token data is itself useless to the Client The ex-change thus supplies access for the Client but no user informa-tion What if our app needed to customize the User Experience(UX) based on the user type For example which membershiplevel the user belonged to a group they were a member ofwhere theywere located or their preferred languageManyappsprovide this type of experience but to enable this customiza-tion we will require additional user information

How To Control User Identity Within Microservices 42

The OpenID Connect Flow

Letrsquos assume that wersquore enhancing the email service client sothat it not only organizes your emails but also stores them andtranslates them into another language In this case the Clientwill want to retrieve additional user data and store it in its ownuser sessions

To give the Client something other than the opaque Token pro-vided in theOAuth flowuseanalternative flowdefined inOpenIDConnect In this process the Authorization Server which is alsocalled an OpenID Connect Provider (OP) returns an ID Tokenalong with the Access Token to the Client The flow is as follows

1 The Client requests access to the Resource Server by call-ing the Open ID Connect enabled Authorization Server

2 The Authorization Server redirects to allow the user toauthenticate

3 The Authorization Server then validates the user creden-tials and provides an Access Token AND an ID Token to theClient

4 The Client uses this ID Token to enhance the UX and typi-cally stores the user data in its own session

5 The Client then sends the Access Token to the ResourceServer

6 The Resource Server responds delivering the data (theemails) to the Client

How To Control User Identity Within Microservices 43

The ID token can contain information about the user such as au-thentication details name email or any number of customuserdata points This ID token takes the form of a JSON Web Token(JWT) a coded and signed compilation of JSONdocuments Thedocument includes aheader body anda signature appended tothe message Data + Signature = JWT

Using a JWT you can access the public part of a certificatevalidate the signature and understand that this authenticationsession was issued mdash verifying that the user has been authenti-cated An important facet of this approach is that ID tokens es-tablish trust between the Authorization ServerOpen ID ConnectProvider and the Client

Using JWT For OAuth Access Tokens

Even ifwedonrsquot useOpenIDConnect JWTscanbeused formanythings A system can standardize by using JWTs to pass userdata among individual services Letrsquos review the types of OAuthaccess tokens to see how to implement secure identity controlwithin microservice architecture smartly

How To Control User Identity Within Microservices 44

By Reference Standard Access Token

A Standard Access Token contains no information outside ofthe network merely pointing to a space where information islocated This opaque string means nothing to the user and asit is randomized cannot easily be decrypted Standard AccessTokens are the standard format mdash without extraneous contentsimply used for a client to gain access to data

By Value JSONWeb Token

A JSON Web Token (JWT) may contain necessary user infor-mation that the Client requires The data is compiled and in-serted into themessage as anaccess token JWTs are an efficientmethod because they erase the need to call again for additionalinformation If exposed over the web a downside is that thispublic user information can be read easily read exposing thedata to an unnecessary risk of decryption attempts to crackcodes

TheWorkaround External vs Internal

To limit this risk of exposure Ideskog recommends splitting theway the tokens are used What is usually done is as follows

1 The Reference Token is issued by the Authorization ServerThe Client sends back when itrsquos time to call the API

2 In themiddle TheAuthorizationServer validates the tokenand responds with a JWT

3 The JWT is then passed further along in the network

In the middle we essentially create a firewall an Authoriza-tion Server that acts as a token translation point for the API

How To Control User Identity Within Microservices 45

The Authorization Server will translate the Token either for asimple Reverse Proxy or a full-scale API Firewall However theAuthorization Server shouldnrsquot be in the ldquotraffic pathrdquo mdash thereverse proxy finds the token and calls the Authorization serverto translate it

Let All Microservices Consume JWT

So to refreshwithmicroservice securitywehave twoproblems

bull Weneedto identify theusermultiple timesWersquove shownhow to leave Authentication to OAuth and the OpenIDConnect server so that microservices successfully provideaccess given someone has the right to use the data

bull We have to create and store user sessions JWTs containthe necessary information to help in storing user sessionsIf each service can understand a JSON web token youhave distributed your identitymechanism allowing you totransport identity throughout your system

In a microservice architecture an Access Token should not betreated as a request object but rather as an identity object Asthe process outlined above requires translation JWTs shouldbe translated by a front-facing stateless proxy used to take areference token and convert it into a value token to then bedistributed throughout the network

How To Control User Identity Within Microservices 46

Why Do This

ByusingOAuthwithOpenIDConnect andbycreatingastandards-based architecture that universally accepts JWTs the end resultis a distributed identity mechanism that is self-contained andeasy to replicate Constructing a library that understands JWTis a very simple task In this environment access as well as userdata is secured Creating microservices that communicate welland securely access user information can greatly increase theagility of an entire system as well as increase the quality of theend-user experience

Part Two OAuth Flowsand Deep Dives

8 Types of OAuth Flows AndPowersby Daniel LindauOriginally Published Here

There are multiple OAuth flows catered to various scenarios

The API space requires authorization in order to secure data ndashthis is a given in themodern era Accordingly implementing thecorrect authorization system is vitally important perhaps evenmore important than the API it is meant to handle authorizationfor

OAuth is a powerful solution for many providers However aswith any tool trsquos only as powerful as it is understood by the userwho chooses it Understanding what OAuth is and having a gen-eral overview of each particular flow is extremely important Inthis piece wersquore going to look at OAuth and give a brief rundown

8 Types of OAuth Flows And Powers 49

of each flow type Wersquoll look at when each flow is appropriateand what its specific use case is

What Is OAuth What Is a Flow

While itmight gowithout saying there is somebenefit to statingupfront exactly what OAuth is OAuth is an open standard fordelegation and authorization on the internet The use case forOAuth is usually a client that needs to access some resourceon behalf of the user To accomplish this delegation an AccessToken is issued The Access Token represents the userrsquos consentallowing the client to access its data on behalf of the user Therequesting granting and life management of this token is oftenreferred to as a flow a term that will be used substantiallythroughout this article

While the first version of OAuth was initially created in 2007as a means to handle authentication on the Twitter API it hassince become extremely popular in a variety of applicationswith scopes ranging from enterprise-level codebases to homeprojects The second version OAuth 20 has become the defacto standard for securely protecting your APIs

Flows Differ On Use Case

TheOAuth specification allows for severalways of obtaining andvalidating tokens and not all flows are meant for all types ofclients The OAuth specification talks about public and privateclients which roughly translates into the clientsrsquo ability to keeptheir credentials safely stored Private clients are typically ap-plications with a backend that can keep a secret to use for au-thenticating Public clients have no means of securely keeping

8 Types of OAuth Flows And Powers 50

a secret such as a Single Page Application (SPA) that usuallydoesnrsquot have a backend

For instance web applications with a backend are consideredprivate clients andSPAsare consideredpublic Thebackendcansecurely keep the secret while the SPA has everything out in theopen

Mobile clients are abit trickier to classify since they are generallypretty good at keeping a secret but itrsquos hard to give them oneThe way the apps are distributed through app stores makes itharder for clients to authenticate in a way for the OAuth serverto trust that it is the correct application For this reason theyare to be considered public By using other means of gettingcredentials like the Dynamic Client Registration it can bemadeinto a private client But more on that later

Obtaining Tokens

There are four base flows for obtaining tokens in OAuth andseveral flows that are defined in sibling specifications Here Irsquolldescribe thebase flowsandothers that I believe tobe important

1 Authorization Code Grant

The Authorization Code Grant or Code Flow is the most widelyused OAuth flow To obtain a token using code flow the clientssend an authorization request to the OAuth server by simplyredirecting the browser to the server The OAuth server makessure that the user is authenticated and prompts the user toapprove the delegation When the user approves a short-livedcode is issued to the client This code can be considered a onetime password or a nonce The client receives this code and cannow use it in an authenticated backend call ndash outside of thebrowser ndash and exchange it for the token

8 Types of OAuth Flows And Powers 51

One thing to mention here is that the user only will enter itscredentials to the OAuth server The user wonrsquot have to givethe credentials to the app it simply enters them to the serverit already knows and trusts This is one thing that OAuth set outto solve

The other benefit is that the token owner passes the browserwhich makes it harder to steal and since the call to exchangethe token is authenticated the server can be sure that it deliversthe token to the correct client

Usually the Code Flow will also allow you to receive a RefreshToken which allows the client to get new access tokens withoutinvolving theuser evenafter theAccess Token is expired Privateclients should only use the Code Flow since the client mustauthenticate itself when exchanging the code

Code Flow The Client consist of two parts the browser and the backend

2 Implicit Flow

The Implicit Flow is a less complicated flow than the Code FlowIt starts out in the same way as the Code Flow with the client

8 Types of OAuth Flows And Powers 52

making an authorization request to the OAuth server The userauthenticates and approves of the delegation but instead ofissuing a code theOAuth server respondswith an Access Token

The downside here is that the token is visible in its entirety andsince it is in the browser the client may handle the token in away that could make it vulnerable

The Implicit Flow is designed for public clients that cannot au-thenticate themselves So the trust here instead lies in a pa-rameter called redirect_uri The OAuth server needs to haveregistered a URL for the client where the response will be sentThe responsewill onlybe sent there so if amaliciousapplicationfools auser into initiatingadelegationprocess the responsewillalways go back to the real application

Since this is for public clients a Refresh Token wonrsquot be issuedThat means that new Access Tokens can only be received byinvolving the user

Implicit Flow The full flow happens in the browser

8 Types of OAuth Flows And Powers 53

3 Client Credentials Flow

In the Client Credentials Flow there is no user It is a flow thatis strictly for server to server communication In this situation aservermust access anAPI as itself Therefore there is nobrowserinvolved and a private client is needed To get an Access Tokenthe client simply passes itrsquos credentials to the OAuth server andreceives the token

No Refresh Token is issued in this flow since the client can justget a new Access Token using itrsquos credentials anyway

Client Credentials Flow A server authenticates itself against the token end-point No user involved

4 Resource Owner Password Credentials Flow

TheResourceOwnerPasswordCredentials (ROPC) Flow is prettysimple The client collects the credentials from the user andpasses them together with its own client credentials The serverresponds with an Access Token and optionally a Refresh TokenSimple right But therersquos a ldquobutrdquo And itrsquos a big one

8 Types of OAuth Flows And Powers 54

ROPC is a flow that defeats one of OAuthrsquos purposes that theuser has to give away its credentials to the app and thus hasno control over how the client will use it The flow is not recom-mended for use if you can use something else Itrsquos only specifiedin the specification to allow for legacy or migration cases ROPCshould be used with care An example could be an enterprisedesktop application that is not easily updated yet needs to ac-cess the API platform

We donrsquot recommend the use of (ROPC) But if you really needto ROPC should be used for private clients only and the clientcould get a Refresh Token

ROPC The client sends users credentials together with its own credentialsOnly for legacy use cases

5 Dynamic Client Registration

While not one of the flows in the core OAuth Spec DynamicClientRegistrationsolvesan importantusecase formobile clientsSince mobile apps are distributed through app stores itrsquos hardto give themacredential to identify themselves uniquely There-fore mobile clients are usually labeled as public

8 Types of OAuth Flows And Powers 55

Dynamic Client Registration tries to redeem that by specifyingmeans for a client to register itself and request a unique cre-dential upon installation It works by letting the client send aregistration token to the OAuth server which generates a set ofcredentials and returns themto the client These credentials canthenbeused inaCodeFlow and theclient cannowauthenticateitself

The registration token can be obtained in multiple ways Eitherby letting the user authenticate itself in an Implicit Flow or byusing the Client Credentials flow with a pre-distributed secret

Outside of the mobile case Dynamic Client Registration can bevery useful for API management platforms that need to be ableto create clients for the OAuth server

6 Assisted Token Flow

The Assisted Token flow is a draft that is not part of the baseflows but it is worth mentioning It is a sibling specification toOAuth that tries tomake it easier for Single Page Applications toobtain tokens It can be hard for those types of applications tohandle Implicit Flow since it relies heavily on redirects InsteadAssisted Token Flow defines a similar flow to Implicit whichinstead uses iframes and postMessage to communicate

Token Management

7 Introspection

Introspection is the way to ask the OAuth Server if a token isvalid Access Tokens are usually passed around by referencemeaning that they do not mean anything for anyone but theOAuth server The introspection clients are usually an API or an

8 Types of OAuth Flows And Powers 56

API gateway of sorts Introspection is a simple authenticatedcall where you send in a token and the response is the data thatbelongs to the token such as the expiration time subject etc

8 Revocation

Revocation is one of the powers of OAuthWithout OAuth a userthat gave away its credentials to an application has nomeans ofretracting that consent The onlyway is to change the passwordwhichmight have bigger side effects than disallowing the app toaccess the userrsquos account

With OAuth the user can decide to recall the consent when-ever by revoking the token In OAuth you have two options forrevocation you can revoke the Access Token which could beseen as ending the current session If there is a Refresh Token itwould still be valid Revoking the Refresh Tokenwouldmake theRefresh Token invalid and any active Access Tokens that camewith it

It is the client that performs the actual revocation with an au-thenticated call Even though itrsquos authenticated public clientscan be allowed to perform revocation

Why Distinguishing OAuth Flows IsImportant

It can seem like there are a lot of similar flows in OAuth buteach flow has its specific use case By these essential flows youshould be able to pick the flow(s) that match your applicationand scenario

Exploring OAuthtools TheWorldrsquos First OAuthPlaygroundby Kristopher SandovalOriginally Published Here

OAuthtools created by Curity is a safe vendor-agnostic place toexperiment with a wide variety of OAuth flows

API security is complex and theunderlying systems that supportit are even more so Getting a grasp on API security requiresunderstanding many underlying components Accordingly anytool that can help contextualize these systems is not only anexcellent educational tool but itrsquos also a good business tool

OAuthtools looks poised to be that solution Developed by Cu-rity OAuthtools breaks down complex OAuth related topics

Exploring OAuthtools The Worldrsquos First OAuth Playground 58

like flowsandscopes intovisuallyunderstandablecomponentsEach flow is understood in context with other flows by takingon this approach So does OAuthtools succeed in depictingsuch complex topics We think so In this chapter we reviewOAuthtools and consider why understanding OAuth flows is sovaluable for securing your APIs

What is OAuthtools

OAuthtools isprincipallyaneducational resourcendashasafe vendor-agnosticplace to learnabout andexperimentwithawidevarietyofOAuth flows Itrsquos designed to informnot toproselytize a singlevendor solution (or in fact a single solution at all as it offers awide variety of different flows to test) Many flows that can betested against a live environment which allows you not only toseewhat each flowdesign looks like butwhat the expected out-put and the various restrictions requirements and functionalcomponents look like from an operational standpoint

The site currently supports nine flows Decode JWT Client Cre-dentials FlowCodeFlowHybrid Flow Implicit FlowROPCFlowDevice Flow Introspection Flow and Userinfo Flow This com-prehensive coverage allows for a wide variety of implementa-tions to be represented throughout your testing

When you first enter the site you are greetedwith the JWT tokenpage This page is a great example of how clarity and brevity arebest used to communicate a ton of info at once The page (andsite in general) is well-designed and simple to understand

The page is broken into three sections representing a common-sense workflow On the left we can see the flows currentlyin use From here we can create delete or switch betweenother flows wersquove configured (as well as filter the current batchof flows by a stated criteria) In the center of the page the

Exploring OAuthtools The Worldrsquos First OAuth Playground 59

workspace allows you to paste a JWT and switch between ahandful of token types including Access Token Refresh TokenID Token Client Assertion User Assertion OpenID Metadataand the ambiguously titled ldquoOtherrdquo

Before one can test a flow an environment needs to be createdThe environment management system here is well-executedboth intuitive and complete

One of the big features here is the inclusion of the WebFingerprotocol The protocol specified by the IETF is a mechanism bywhich information and metadata can be discovered automati-cally througha simpleURLWhileWebFinger is the specifiedpro-tocol for OpenID Connect its inclusion here was a smart movein terms of user experience ndash it lowers the barrier of entry byreducing the amount ofwork thatmust be donewhen creating atest environment something that is still a bit of a chore in othersolutions

After the proper URL has been enteredWebFinger can automat-ically populate the rest of the information in the environmentspanel listing the endpoints the exposed scopes any publishedkeys the possible mechanisms for authentication and the ex-pected response types not to mention the metadata itself

Within this system is a clientmanagement panel aswell A clientwill need to be created to act on the environment This is easilydone by simply entering the desired client IDname a secretphrase and then selecting what flows to use Included flowshere are Code Flow Implicit Flow Hybrid Flow Client Creden-tials Flow ROPC Flow Introspect andDevice Flow Additionallyyou can choose whether or not the client can be framed at thispoint meaning it can be framed in an HTML element

Once all of this has been set up we can start creating flowsFlows in OAuth are methods of authorization that are oftenstarkly different from one another so the inclusion of a greatmany flows here is great ndash the user can familiarize themselves

Exploring OAuthtools The Worldrsquos First OAuth Playground 60

with some of the more esoteric or single-purpose flows whilehaving access to general flows as well

As stated previously you can select from Decode JWT ClientCredentials Flow Code Flow Hybrid Flow Implicit Flow ROPCFlow Device Flow Introspection Flow or Userinfo Flow to starttesting a flow

In this case wersquove used a test JWT as provided by jwtio Herewe can see the fundamental simplicity of this site and the clarityit gains To the left we have all of our flows and the prompt toadd more In the center we have our JWT and a wide varietyof options as to how we define that JWT to this system On theleft we have a very clean efficient way of visualizing what ishappening during this decoding

While this is by far the simplest of these options it does ex-pose a few things First and foremost it exposes how a JWT iscomposed and what part of the JWT is responsible for whatThis graphical representation of a data-heavy item is extremelyuseful and when combined with the greater system of flowshelps toset thebasemoving forward forhowthe restofour flowslook and act

Education vs Proselytization

As we discuss OAuthtools we should recognize the differencebetween education tools versus the proselytization of specificsolutionsWhen creating test cases example environments andso forth itrsquos very easy to fall into the trapof designing formarket-ing rather than designing for knowledge While therersquos nothingwrong per se with designing forward-facing materials for mar-ketinguses (and in fact is somewhatexpected) these toolsmustat their core do one thing ndash educate

This is something that OAuthtools does reallywell Because this

Exploring OAuthtools The Worldrsquos First OAuth Playground 61

system was designed first and foremost to educate and giventhat itrsquos free to use and explore the value of the tool for educa-tional purposes cannot be overstated OAuth can at times bequite complex ndash having the ability to play with it safely for freeis great Doing this without also being inundated with upsellsis even better and really suggests a user-experience mindset ofteaching not preaching

Conclusion

OAuthtools is a great offeringandprovides awonderful environ-ment from which a wide range of testing can be done in a safezero-cost environment In terms of tools that expose complexunderlying systems this solution does so in perhaps one of themore elegant and effective manners

This tool is greatnotonly for exposing these flows to those tryingto test code or approach against the flows themselves but forexposing the common layperson to what these flows look likehow they work with a variety of pieces of data and ultimatelyhow OAuth in general looks feels and functions

Strategies for integratingOAuth with API GatewaysbyMichal TrojanowskiOriginally Published Here

Choose the rightOAuth flow for your specific API gateway scenario

Securing your APIs with OAuth proves that you have adopteda mature security model for your service However setting upOAuth in front of your API is not a trivial task There are usuallymany architectural questions to be answered more than theusual ldquowhichauthorization server to chooserdquoor ldquohowtovalidatea tokenrdquo

Developers often encounter a problemwhen their solution con-sists of a service mesh hidden behind an API Gateway Shouldthe API Gateway be involved in the process If so how can ithelp

Strategies for integrating OAuth with API Gateways 63

In this chapter wersquoll demonstrate the different approaches ofintegrating OAuth with an API gateway Wersquoll also showcaseexamples of how these approaches can be used with differenttypes of API gateways

Two Strategies for Sharing Tokens

There are twomain strategies for sharing access tokenswith theoutside world

bull You can share the JSON Web Token generated by the Au-thorization Serverwith any external client In this scenariothe same token is used externally and internally by yourAPIs

bull You can share externally an opaque token which is thenexchanged for a JWT This means that an opaque token isused externally but internally your APIs work with a JWT

For the best security the latter option is typically the recom-mended choice In this scenario you donrsquot share any data em-bedded in your access token with any external clients The ac-cess token contents are meant for your API but if you share aJWTwith external clients anyone can decode the token and useits content

ProblemsWith Externalizing a JWT

Exposing a JWT with external clients can lead to privacy and se-curity issues Moreover it can complicate your implementationWhen you share a JWTwith the external clients developersmaybe able to decode the tokens and start using its contents eventhough the tokens are intended just for your APIs This could

Strategies for integrating OAuth with API Gateways 64

lead to situations where making any changes in the contents ofthe token can break existing implementations The contents ofa JWT token become a contract between you and the externaldevelopers and breaking change should be avoided

In the first approach the integrationwith the API Gateway is notthat crucial TheGateway just forwards theJWT to theAPIwhichcan then validate it Though you can let the Gateway do someof the validation tasks

If you decide to implement the recommended approach properintegration with a gateway becomes more critical To validatethe token and read its contents a JSON representation mustbe obtained The exchange for a JWT can be done by everymicroservice which uses the token but it can unnecessarilyincrease the traffic load and complicate the architecture as eachservice should be capable of performing the exchange Thatrsquoswhy itrsquos much better to let the API Gateway handle this ex-change Now letrsquos explore different ways to integrate with APIgateways

Approaches for IntegrationWith APIGateways

A few approaches can be used when integrating with an APIgateway They will depend on the token sharing strategy youchoose

Strategies for integrating OAuth with API Gateways 65

JWT Validation

If you decide to share JWTs with the outside world it is goodto have your API Gateway perform a validation of the incomingtoken The Gateway can check the signature and perform someinitial validation of the contents of the token For example itcould assess the validity of the time-based claims the issuer theaudience or some required scopes

Using JWT Validation an API Gateway can reject requests withinvalid tokens limitingunnecessary traffic thatwouldotherwisereach your internal network

Strategies for integrating OAuth with API Gateways 66

Phantom Token Approach

The Phantom Token Approach is one of the options you canimplement if you want to share opaque tokens externally butuse JWTs between your internal services The opaque token isexchanged for a JWT using the introspection pattern The APIgateway handles this exchange

With this approach all the services behind the Gateway donrsquothave toperform the exchange themselves limiting network traf-fic A Phantom Token strategy is easier to maintain than havingall services handle introspection on their own as there is onlyone point fromwhich the Authorization Server is queried

Strategies for integrating OAuth with API Gateways 67

Split Token Approach

The Split Token Approach is another option in which an opaquetoken is exchanged at the API Gateway for a JWT In this patternthe Authorization Server splits the generated token into twoparts

bull The signature of the JWTbull Head and body of the JWT

Thesignature isusedas theopaque tokenbyanyexternal clientsThe other part is sent to the API Gateway togetherwith a hashedsignature where it is cached Upon a request the API Gatewayuses the incoming part of the token to look up the rest of it in itscache and then glues them back together to create a completeJWT The resulting JWT is added to the request forwarded to anyservices behind the Gateway

This approach helps you further limit the network traffic neededto exchange the opaque token for a JWT as no additional re-quests to the Authorization Server are required

Strategies for integrating OAuth with API Gateways 68

Example API Gateway Integrations

Should you decide to integrate your OAuth solution with an APIGateway the approach you choose depends on the type of theAPI Gateway that you use There are many different solutionsavailable on the market and many companies are even us-ing their own proprietary gateways Below wersquoll examine threecommercial API Gateway implementations

Cloudflare CDNs as Gateways

Cloudflare CDN provides enough functionality to be used as adistributed API Gateway It is a Gateway spread across multipledata centers and regions with access to a shared key-value storeand capable ofmakingmodifications to requests and responsesthrough lambda functions

If you use Cloudflare or your Gateway shares similar traits thebest approach would be to use the Split Token Approach es-pecially if the Authorization Server is deployed in a substantiallylower number of locations Thanks to the Split Token Approachthe Gateway does not have to query the Authorization Server onevery request which would otherwise considerably slow downthe requests given the servers are in different centers across theworld

When choosing the Split Token Approach one thing to consideris that the Gateway needs access to a shared cache one that canbeeasilypopulatedby theAuthorizationServer andaccessedbyall the distributed Gateway instances

Nginx On-Premise Gateways

Nginx is an example of an API Gateway that is installed on-premise If this is the case for your Gateway solution you should

Strategies for integrating OAuth with API Gateways 69

consider implementing the Phantom Token Approach espe-cially if the Authorization Server that you use is installed in thesame data centers as the Gateway

In such a situation the additional request needed to introspectthe token wonrsquot give much of an overhead to the request Whatis more in this scenario you will not necessarily need a sharedcache Even if you want to cache responses from the Authoriza-tion Server this can be done by each of the Gateway instanceson its own

Google Apigee A Diverse Solution

The answer to the question of which integration pattern is bestin a particular scenario depends on the Gateway features ratherthan the concrete product or vendor For example in the case ofGoogle Apigee you could either use the cloud version or installyour instance on-premise Thus choosing theOAuth integrationapproach will depend on the way Apigee is used In the cloudenvironment it will probably be better to use the Split TokenApproachwhereaswith theon-premise installation youwouldprobably go with the Phantom Token Approach

Conclusion

You can use a few different approaches to integrate OAuth withan API Gateway The solution used should be chosen dependingon the features of your API Gateway When deciding betweenOAuth integration styles two key points to consider arewhetherthe Gateway is distributed or centralized and whether the Gate-way has reasonable access to a shared cache

Although sharing JWTs with external clients may seem straight-forward to implement remember that it is not a good practice

Strategies for integrating OAuth with API Gateways 70

from a security perspective You should avoid it as it lowersyour security and privacy and may lead to problems with yourintegrators

Assisted Token Flow TheAnswer to OAuth Integrationin Single Page Applicationsby Thomas BushOriginally Published Here

OAuth is an incredibly popular internet standard for grantingapps and web services access to the information available onotherwebsites Though the implementation is complex thepremiseis simple you tell a website you want to access its data you loginwith theuserrsquos details andoff yougomdashbutwithout somekindof protocol the process would be a whole lot more complicated

There is one drawback in the current core version of OAuth anditrsquos increasingly evident with the recent trend towards buildingsingle page applications (SPAs) The issue is that designing a

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 72

seamless secureOAuth solution is difficultwithout abackend todo the heavy lifting and by definition single page applicationsdonrsquot have onehellip

Below wersquoll follow along with Curity solutions architect DanielLindau ashepresents the solution toOAuthusage in singlepageapplications following a presentation he gave at The Austin APISummit in Texas 2018

Implicit Flow The Status Quo for OAuthin Single Page Applications

The current method of choice for handling OAuth delegationwithin single page applications uses the implicit flow mdash alsoknown as the client-side flow

Itrsquos simple just redirect thebrowser to theauthorizationserverwhere the user directly authenticates and gives the app accessbefore returning to the application with an access token em-bedded in the URL Then the service can parse the URL for thetoken and immediately start using it

Therersquos no doubt that this is a messy approach Redirects areinherently counter-intuitive if the goal is to build a single pageapplication Whatrsquos more you need to design an architecturewhereby the application can seamlessly resume execution afteryoursquore done with all the redirects Then therersquos the question ofstoring your precious access token in a secure way

Daniel says that Curity typically works with developers whoarenrsquot so familiar with OAuth they donrsquot exactly know the bestpractices for storing and using these tokens Therefore itrsquos im-portant to promote a more failproof alternative

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 73

The iFrame A Coffin for Your OAuthDelegation

Anobviousworkaround toall theproblems causedbya redirect-powered implicit flow is to hide away your OAuth implementa-tion inside an iFramemdash an inline frame

Exactly as it sounds tucking away your OAuth in an iFrame is abit like putting it in a coffin The reason is that an iFrame keepsyourOAuth flowand the rest of your application separatewhichcanmake it pretty difficult to communicate between the two

Another problemwith using iFrameswhich coffins donrsquot exactlysuffer from is that they can be accessed from multiple placesIn the interests of secure authorization yoursquoll probably needto design it such that the frame can only be accessed from theactive page

So whatrsquos the solution

Assisted Token Flow iFrame IntegrationDone Right

CurityhasbuiltOAuthsolutions to their customersrsquo varyingneedsand constraints in a range of ways While each case was slightlydifferent a common denominator was the usage of iFrames mdashbut with precautions taken to avoid the associated problems

Creating similarOAuth integrations timeand timeagaingave theteam a brilliant idea why not standardize the process of OAuthdelegation within an iFrame

Thatrsquos how Assisted Token Flowwas born Itrsquos a draft specifica-tion built onto OAuth mdash which is to say that it uses everything

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 74

that is today OAuth mdash but adds new flows and endpoints tofacilitate usage on single page applications

The protocol uses iFrames for communication between the par-ent page and OAuth server which prevents the pesky redirectswe commented on earlier and JavaScriptrsquos postMessage func-tionality for communication between the frame itself and theparent page

Amuch-welcomedadditionofnewendpointsallowed thedevel-opers to remove unnecessaryOAuth parameters streamliningthe entire delegation process This is an important feature as itmakes page-iFrame interactions much easier to follow

The result is a flowwhereby only the client_idparameter needsto be communicated between the iFrame parent page andauthorization server mdash any other parameters are optional

In the event that other parameters are used the Assisted TokenFlow protocol also offers parameter validation within the im-plementation mdash on the side of the OAuth server mdash which cutsdown on any excess back-and-forth between the applicationand authorization server

Token Grants with Assisted Token Flow

The beauty of using a standard for OAuth integration is thatevery implementation uses the same workflow mdash in this casewith a simple but effective design

Letrsquos look at how tokens are granted with Assisted Token Flowwhen the user is already authenticated versus when the userhasnrsquot yet authenticated

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 75

Assisted Token Flow for an Authenticated User

With Assisted Token Flow the workflow for an already authenti-cated user is extremely straightforward

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server serves a near-empty HTML page to theiFrame including a postMessage scriptwith the result of thetransaction

4 The page is loaded in the iFrame and a postMessage is per-formed sending a success message along with the accesstoken to the parent page

In comparison to coreOAuth the primary advantage here is thatAssisted Token Flow doesnrsquotmandate the inclusion of a scopeparameter (or any other parameter beyond client_id for thematter) if the user doesnrsquot specify a scope Assisted Token Flowgrants access to all possible scopes

Assisted Token Flow for an Unknown User

AssistedToken flow for auserwhohasnrsquot yetbeenauthenticatedis similarly easy with a few extra steps

1 Theapplication requirespermissionatanexternal resourceserver

2 The page opens a hidden iFrame and points it to the re-source server with just the client_id parameter

3 The OAuth server sends a more detailed HTML page to theiFrame including a postMessage script that asks the parentpage asking for the login details

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 76

4 The iFrame is made visible to the user for authentication(eg as a usernamepassword dialog) and the user logs in

5 The application then retrieves data as necessary per thesteps for an authenticated user

Again Assisted Token Flow shows the benefit of not needingany extra parameters while it also shows how simple OAuthintegration can be made when the iFrame aspect is taken careof

Security Precautions in Assisted TokenFlow

As we mentioned earlier there are few security constraintsapparent in using OAuth on single page applications Two of themoremajor issues are the security of the iFrame itself as well asthe storage of access tokens

Herersquos theprecautions thatAssistedTokenFlowhas takenagainstany such vulnerabilities

iFrame security

Therersquos adouble-barreledapproach tokeeping the iFrames safefor starters the client is registered at the OAuth server to aparticular domain (which is enforced with HTTP headers andcontent security policies) and secondly thedomain is specifiedin the postMessage to prevent external access to the token

Token storage

As for tokenstorage thereareonly really twooptionslocalStorageaswritten intoJavaScript or cookie storageCurity recommends

Assisted Token Flow The Answer to OAuth Integration in Single PageApplications 77

cookie storage as it allows the access token to be stored witha domain path and expiry time mdash so all interactions with theendpoint will send an access token for the OAuth server to acton

Conclusion Assisted Token FlowMakesOAuth Easy on Single Page Applications

Assisted Token Flow makes OAuth easy especially for thosewhorsquove struggled to find a sleek but secure way to use it withinsingle page applications

It takescareof iFramesand tokenstorage createsanew lightweightendpoint with just one mandatory parameter and even vali-dates any parameters for you Best of all the majority of this isachieved server side so the developer doesnrsquot have to worryabout all the basics in their implementation

The result is an OAuth protocol which is a heck of a lot easier touse but sacrifices no functionality

And just how easy is it Herersquos an 8-line JQuery implementationwhere Curity sets up the origin and client_id initiates the libraryand off we go

1 var settings =

2 clientId client-assisted-example

3 autoPrepareJqueryAjaxForOrigins [httpsexamplecom]

4

5

6 var assistant = curitytokenassistant(settings)

7

8 $(document)ready(function ()

9 assistantloginIfRequired()

10 )

Using OAuth Device Flow ForUI-Incapable Devicesby Kristopher SandovalOriginally Published Here

As the internet growsandmoredevices become interconnectedauthorization is becomingmore complex

Early implementations of online services were easy to authorizeagainst since they were tied to desktops butmodern authoriza-tion must consider varying environments from mobile apps toIoT scenarios Many of our new devices such as smart TVs andvoice-controlled speakers donrsquot have traditional UIs like webbrowsers

The growing prevalence of input-constrained devices leads toa quagmire concerning howproviders should actually authorize

Using OAuth Device Flow For UI-Incapable Devices 79

these devices What is a secure way to enter username andpassword in UI-incapable systems

Today wersquore going to look at where this problem comes fromand what we can do to fix it Wersquoll cover three unique OAuthflows to see how they stand up to solve the issue at hand TheResourceOwnerPasswordCredentials FloworROPC theOAuthCode Flow and the OAuth Device Flow Wersquoll see which is thesafest way to incorporate identity into these new environmentsto ensure that even your living room devices maintain a high-security level

This chapter follows a presentation given by Jacob Ideskog ofCurity at the Nordic APIs Platform Summit View the slides here

Identifying the Problem

To get to the root of the issue letrsquos take a hypothetical caseLetrsquos assume that we want to stream music onto a TV from adata source In this case from amusic streaming provider wersquollcallMusicbox Musicbox requires authorization for all streamingsessions and in our hypothetical situation this applies to our TVas well

To get Musicbox to stream on our TV we have a few optionsWe can use an app built for this specific purpose mdash this is com-monplace onmanymodern smart televisions and offers what isessentially awebbrowseroverlay that handles authorization Todo this we would use a type of flow called the Resource OwnerPassword Credentials (ROPC) Flow

Using OAuth Device Flow For UI-Incapable Devices 80

ROPC OAuth Flow

In this approach the ROPC flow has the resource owner issue aPOST request with a form URL encoded body containing the usercredentials to the OAuth server This server is at the streamingservice level and utilizes this credential to grant access to theinternal systems This is done by generating an OAuth tokenwhich is then handed back to the TV and passed on to thestreaming service for each request This is a very traditionalOAuth flow but it has some significant problems in our use case

First therersquosamajor securityconcernMost streamingprovidersare not going to want a TV utilizing proprietary codebases andsystems to have the login credentials for all their users whochoose to utilize the app The issue of trust is especially rel-evant for client apps built on the streaming service API thatare developed by third parties Even if the application is anofficial one this creates amajorpoint of failure thatdramaticallyexpands the attack vector on the API itself and all but invitessophisticated token attacks

More seriously however therersquos the fact that the ROPC flowsimply was never designed for this application While it seemsa perfect fit the ROPC flow is designed for legacy systems ndashutilizing it for smart TVs is an incorrect application and actuallyworks against OAuth As Jacob states

ldquoThe resource flow is not really meant for thishellip Itrsquosactually there to just solve legacy problems If wersquorebuilding a new system we should never use it Itrsquoswhy it has built-in antipatternsrdquo

Using OAuth Device Flow For UI-Incapable Devices 81

OAuth Code Flow

The whole purpose of OAuth is to not give passwords to 3rdparties which this procedure would do Consider we ignoreROPC and go for a more regular OAuth code flow where thebrowser is used to send a GET request and an authorization pageis used as a prompt

In this case we still run into a single fact that we canrsquot avoidndash all of this flow was meant for smart devices more capablethan our constrained TV The browser would be terribly slowand entering a username and password with a remote controlis inefficient As such even if these were acceptable solutionsthey would result in bad user experiences

A Question of User Experience

Even ifwecould ignore the technical issues inherent in this issuethe fact is that using the solutions often results in frustration be-cause of the limitations on input and interaction Utilizing a tinyremote control to enter in a complicated usernamepasswordpair and deal with any additional prompts that might pop up isultimately quite cumbersome

Things get worse if therersquos no controller at all Imagine thatinsteadof our smart TVwersquoreutilizinga speaker suchasanAlexaintelligent speaker In this case we no longer have a screen ora mode of easy input and our issue becomes that much morecomplex

What is our solution then Luckily therersquos a new OAuth flowbeing standardized that couldhelp here Insteadof theResourceFlow or the Code Flow letrsquos turn our attention to the OAuthDevice Flow

Using OAuth Device Flow For UI-Incapable Devices 82

OAuth Device Flow

OAuth recognized the issue inherent with authorization usingconstrained devices and has drafted a standard known as theOAuthDeviceFlowThestandard currentlyunderdraft as ldquodraft-ietf-oauth-device-flow-06rdquo is specificallydesigned forUI-incapabledevices such as browserless and input-constrained systemsIt therefore should be a good method for devices like our smartTV or voice-controlled system

The flow looks similar to the traditional OAuth solutions butbreaks away quite significantly at a very key stage

In this solution we have an API the OAuth server and the TVrequesting the content The TV starts by sending aDevice Autho-rizationRequest passingwith it the scopeand theclient IDof therequesting device From here the OAuth server responds with adevice code a user code and a verification URI This also hasan expiration timer and an interval that limits the exploitabilitypossible in such communication

From here on out the OAuth flow breaks into a new form Theuser visits the verification URI enters in the requested data(typically the user code) and authorizes the device functionDuring this time the OAuth server is told to wait for the userand to expect the user code A countdown is initiated that willautomatically revoke the validity of the code passed if time issurpassed giving the data an expiration time for securityrsquos sake

During the time the user is entering the code the device con-stantly polls the OAuth server on a set interval and once theOAuth server receives the credentials this polling is respondedto with an authorization token This token is then handed offfrom the device to the API to stream content

Using OAuth Device Flow For UI-Incapable Devices 83

How is this Different

ldquo[This discussion is] about how we can work withdevices that are not as smart as wersquore used tohellip Itrsquosreally about getting identity into a new box that wehavenrsquot thought about beforerdquo

This flow is different in some pretty significant ways First andforemost there is the obvious fact that authorization of this typeoccurs outside of the device band The device itself in this casethe TV is not the flowing credential system that accepts logininformation ndash the user uses an external system such as theirphone laptop computer etc to verify the request and gainaccess

This also means that access is not restricted to just physicallyentering in the login information ndash logins can occur using NFCBluetooth and biometrics and the code requested can be givenusing as many solutions This is limited of course to nearbymethods ndash OAuth does not allow this to expand outside of thenear field as allowing access from out of country or out of citycould result in a wide attack vector

This flow also allows for refresh tokens to seamlessly request areauthorization meaning usersmake a single request and thenautomatically re-apply for this authorization without having toenter their credentials This makes the entire authorization anduser process not only technically more secure and effectivebut better in terms of user experience mdash this of course was amajor concern for other code flows and as such represents asignificant advancement

Using OAuth Device Flow For UI-Incapable Devices 84

A Solution of Gaps

Setting up authorization for devices with limited user interfacespresents an interesting UX challenge The problem is not goingaway Until every device utilizing a service is either limited bypolicy or by reality to support advanced interactions and soft-ware suites the issue will only worsen

We live in a world of smart services but the devices we useto interact with them are often quite dumb Ultimately usingthe OAuth Device Flow is the best current solution we have ndashthe draft solution is effective and offers a wide range of optionsfor authorization As we saw in Jacobrsquos talk itrsquos a standardizedapproach on how to login to a non-UX-friendly device

SCIM Building the IdentityLayer for the Internetby Bill DoerrfeldOriginally Published Here

In 2014 aworking group reached a consensus for v20 of SCIMmdasha simple yet powerful standard thatmore andmore large digitalorganizations are beginning to adopt for cross-domain identitymanagement Now the SCIM specifications are standardizedofficially published by the Internet Engineering Task Force asRFC7643 and RFC7644

In this chapterwe introduce theSCIMprotocol track theprogressof the standard and identify new resource retrieval standardsdocumented in the September 2015 RFC Guided by IETF work-ing group contributor ErikWahlstromwersquoll introduce the basicsof SCIM and identify lessons learned from the design of the SCIMAPI that have directed further iteration of the project as awhole

SCIM Building the Identity Layer for the Internet 86

What is SCIM

Enterprises are extremely distributed mdash applications and dataare sent and stored all over the place from cloud servers partersystems to internal servers Throughout a scattered environ-ment itrsquos easy to lose control of where the data is But as dataprivacy becomes more and more a heated issue regaining con-trol of identity is a top priority

Enter SCIM SCIM (System for Cross-Domain Identity Manage-ment) was developed to standardize how companies createupdate and delete identity data mdash a standard for the life cyclemanagement of online identity by allowing a standard methodfor exchanging identity to other partners or systems

SCIM is a lightweight provisioning protocol that specifically de-fines two things

bull Scheme the identity profile could be a user group ma-chine or other resource entity SCIM defines what thoseresources look like and how they are structured

bull Protocol the method of transport how do we send userdata to different systems

Standardized by the Internet Engineering Task Force (IETF) con-tributors to the project include companies like Nexus OracleSailPoint SalesforceGoogle CiscoPing Identity andMicrosoftIt seems like the SCIM standard is getting the hype and involve-ment it deserves indicating a roadmap to future ubiquity

Use Cases for SCIM

There are two distinct systems involved in using SCIM a systemthat is either creatingor readinguser identity data and the sys-

SCIM Building the Identity Layer for the Internet 87

tem that stores this data In a world of competing regulationsyou often need varying levels of trust between parties In Ger-many for example in order to send personal information youneed user consent every time you do it SCIM doesnrsquot go downthis rabbit hole not concerning itself with legal obligations Itassumes the right to share information is existent between thetwo players Assuming this trust has already been establishedbetween the two entities using other security methodologiesSCIM can be used to exchange identity information for a varietyof use cases Here are three examples

1 Synchronization Across Corporate Systems

What happens when a new employee joins a corporation AnHR manager will likely add a new user profile to their databaseAs it would be tedious to create redundant profiles in all cloudand internal systems the company ideally wants to automati-cally synchronize data across all systems Standardizing iden-tity control with SCIM enables a method for creation and re-moval of universal identity data

2 On-Demand Provisioning

For companies using CRMs like Salesforce you end up payinga monthly fee per each account But what happens when em-ployees leave sales teamschange and thus thenumberof usersaltered SCIM could help companies save money by instigatingon-demand provisioning wherein when a Salesforce account iscreated a SCIM account is created When a user quits the ac-count can easily be removed andoperational costs decreased

3 Inter-Clouds Transfer

Have you ever had difficulty switching between accounts inGoogle Apps Even more troublesome is transferring existing

SCIM Building the Identity Layer for the Internet 88

company assets between various cloud platforms Suppose acompany wanted to migrate from Office 365 to Google mdash therereally isnrsquot an easy way to do this If all providers supportedthe SCIM standard however user information could be movedabout more easily

Schemas amp SPML Comparison

Similarly tohowwebbrowser single sign-on (SSO)canbeachievedby technologies likeSAMLandorOpenIDConnect prior toSCIMthere have been attempts at standardizing cross-domain iden-tity control SPML developed by OASIS has been an open pro-tocol since 2003 However it is heavy XML based and doesnrsquotdefine a schema mdash meaning that every time data is sent sys-temson theother enddonrsquot really understandwhat the resourceis supposed to look like

SCIM on the other hand allows developers to create their ownschemas anddefines twooff thebatuserandgroup Standardshave also beenmade to extend this within the core specificationwith the enterprise user schema to cater to an ITmanager withuniqueprivileges SCIMalso has a schema that defines schemasenabling systems to speak with one another to find out whatresources they support andwhat they look like Ameta schemahelps determine the capabilities of each server can you createusers Filter users This is a big difference between SPML andSCIM

The SCIM API

SCIM is handled via a REST-based API for provisioning changeandde-provisioningmdashall ofwhich lie outside the realmofOAuthand SAML With the rise of web APIs and microservices SAML

SCIM Building the Identity Layer for the Internet 89

has been deemed by some as too heavy with itrsquos verbose XMLSCIM rather calls for authentication and access tokens in com-pact JSON passed via HTTP headers

TheSCIMAPI canbe tested fromacommand line is cURL friendlyand firewall-friendlyWahlstromnotes that REST-based APIs canbe proxied through a firewall and can easily implement stan-dard security using SSL and TLS certifications and data encryp-tion SCIM standard doesnrsquot necessarily define an authentica-tion method but recommends OAuth2

The SCIM core schemamentions 5 unique endpoints

Resource Endpoint Operations DescriptionUser Users GET POST

PUTPATCHDELETE

RetrieveAddModifyUsers

Group Groups GET POSTPUTPATCHDELETE

RetrieveAddModifyGroups

ServiceProviderConfigura-tion

ServiceProviderConfigsGET Retrievethe ServiceProviderrsquosConfigura-tion

Schema Schemas GET Retrieve aResourcersquosSchema

Bulk Bulk POST BulkmodifyResources

Reformatted from SCIM API documentation

For example posting to the Users endpoint can be used to cre-ate a user In this case a developer would receive an HTTP 201successful response that includes an ID mdash a unique identifiercreated for each resource that alsoobtains its ownURL This acts

SCIM Building the Identity Layer for the Internet 90

as a permalink allowing a developer to access the same userinformation from a GET response where the user info is alwaysstored regardless of future edits Increasing discovery with thehelpof schemas is essential for partner-partner communication

As user storages can be huge SCIM specifications include fea-tures like filtering paging and sorting Next wersquoll explore someother features and seewhy thesewere standardized by the SCIMworking group

Features

As Wahlstroem describes they have gone through many itera-tions of SCIM After many decisions and voting (which often in-volved group humming to reach a consensus) the IETF workinggroup reached standards for the following feature sets Take-aways from these design lessons could definitely apply to otherdevelopment scenarios so take heed

bull Extensibility In developing a standard you canrsquot pleaseeveryonemdashtherewill inevitablybeoutliers that request forextended features outsideof theproject scope To this endtheSCIMteamembraced the80-20 rule only specifying themost common 80 of use cases Focusing on deliveringcore cases is essential for designing standards as 20percentile corner cases often take the bulk of your timeand are far harder to implement

bull Versioning of API and Schema SCIM standards place theversioning of the API in the URL This means that a recordof versioning is tracked for each specific resource pro-viding a historical record for all identity entries Thoughthe team considered versioning of API in the header theyopted for URL to retain the permalink for permanent pro-file discoverability in a single fixed location This makes it

SCIM Building the Identity Layer for the Internet 91

easier to understand for implementers and easy to trackrecords with v1Usersusername v2Usersusername andso forth

bull WeakETags for Versioning ofUser Data ETags are used alot in the web world like for caching within your browserfor example In SCIM the HTTP function of weak ETags isused to track the versioning of specific files Weak ETagsallow systems to hold the same data even across differentformatting options Such may occur if a new developerusing a variant JSON parser changes the placement of twodifferent attributes Weak ETags allow systems to knowthat data is the same

bull Error Handling Defining error codes can be a tediousprocess but it is worth it to increase the satisfaction ofthe end developer Users donrsquot like staring blankly at a 404Errormessagemdasherror responsesneed tobemachine read-able and human readable which is why the group definesrobust detailed error codes in the SCIM specification

bull HTTP Method Overloading Some firewalls and proxiesdonrsquot likeallHTTPverbsmdashoften servers and client serversdonrsquot support DELETE or PATCH calls So the SCIM standardsolves this by allowing a POST call to be made with anX-HTTP-Method-Override DELETE function mdash an importantkey in allowing requests to be made to different serviceswith varying verb support

Conclusion Progressing a NeededStandard

A huge benefit of SCIM is that customers can own their owndata and identities Simplified Single Sign On (SSO) is an im-portant step for the cloud and increasing interoperability acrosssystems SCIM is an important step for privacy and according

SCIM Building the Identity Layer for the Internet 92

to Wahlstroem a vital step in building an identity layer of theinternet According to the latest Request for Comments ldquoSCIMrsquosintent is to reduce the cost and complexity of user managementoperations by providing a common user schema an extensionmodel and a service protocol defined by this documentrdquo

Stay tuned for further articles in which we will dive deeper intousing the SCIM standard to create user accounts on a virtualservice

Other Resources

bull SCIM Home Pagebull SCIM Request for Comments 7644bull Nexusrsquos SCIMRFC Announcementbull IndependentID Phil Huntbull SCIM Tutorial Ping Identitybull Introduction toSCIMPresentationSlides TwoboTechnolo-gies

bull ManagingUser Identityacrosscloud-basedapplicationwithSCIM

bull SCIM Email Discussion Thread IETF

Part Three The Role ofIdentity

OAuth 20 ndash Why Itrsquos Vital toIoT Securityby Kristopher SandovalOriginally Published Here

OAuth 20 is vital to IoT security The internet is fundamentallyan unsafe place For every service every API some users wouldlove nothing more than to break through the various layers ofsecurity yoursquove erected

This is no small concern either mdash in the US alone securitybreaches cost companies over $445 billion annually As the In-ternet of Things (IoT) grows this number will only climb

The problem is our considerations concerning security are formodernweb services andAPIsmdashwe rarely if ever talk about thecoming wave of small connected and unconnected IoT devicesthat will soonmake this an even greater concern

OAuth 20 ndash Why Itrsquos Vital to IoT Security 95

From the connected fridge to the smartwatch the IoT is encom-passing many new web-enabled devices coming to the marketAs wersquore designing new API infrastructures Jacob Ideskog be-lieves that the ldquoIoT is going to hit us hard if wersquore not doinganything about itrdquo

Thankfully therersquos a great solution by the nameofOAuth OAuth20 is one of the most powerful open authorization solutionsavailable to API developers today Wersquore going to discuss OAuth20 how it functions and whatmakes it so powerful for protect-ing the vast Internet of Things

What is OAuth 20

OAuth 20 is a token-based authentication and authorizationopen standard for internet communications The solutionfirst proposed in 2007 in draft form by various developers fromTwitter and Magnolia was codified in the OAuth Core 10 finaldraft in December of that year OAuthwas officially published asRFC 5849 in 2010 and since then all Twitter applications mdash aswell as many applications throughout the web mdash have requiredOAuth usage

OAuth 20 is the new framework evolution that was first pub-lished as RFC 6749 alongside a Bearer Token Usage definition inRFC 6750

What Does OAuth Do

While by definition OAuth is an open authentication and autho-rization standard OAuth by itself does not provide any protocolfor authentication Instead it simply provides a framework fordecisions andmechanisms

OAuth 20 ndash Why Itrsquos Vital to IoT Security 96

ldquoOAuth does nothing for authentication So in orderto solve this for theweb we need to add some sort ofauthentication server into the picturerdquo

That being said it does function natively as an authorizationprotocol or to be more precise as a delegation protocol Con-sider OAuthrsquos four actors to understand how it accomplishesthis

bull Resource Owner (RO) The Resource Owner is the entitythat controls the data being exposed by the API and is asthe name suggests the designated owner

bull AuthorizationServer (AS) TheSecurityTokenService (STS)that issues controls and revokes tokens in the OAuth sys-tem Also called the OAuth Server

bull Client The application web site or another system thatrequests data on behalf of the resource owner

bull ResourceServer (RS) Theservice thatexposesandstoressendsthe data the RS is typically the API

OAuth provides delegated access to resources in the followingway Below is a fundamental flow inOAuth 20 known as implicitflow

bull The Client requests access to a resource It does this bycontacting the Authorization Server

bull The Authorization Server responds to this request with areturn request for data namely the username and pass-word

bull The Authorization Server passes this data through to anAuthentication solution which then responds to the Au-thorization Server with either an approval or denial

bull With approval the Authorization Server allows the Clientto access the Resource Server

OAuth 20 ndash Why Itrsquos Vital to IoT Security 97

Of note is that OAuth 20 supports a variety of token types WS-Security tokens JWT tokens legacy tokens custom tokens andmore can be configured and implemented across an OAuth 20implementation

Unique IoT Traits that Affect Security

NowthatweunderstandOAuth20 and thebasicworkflowwhatdoes it mean for securing the Internet of Things (IoT) Well theIoThas a fewunique caveats that need tobe considered Ideskognotes that IoT devices are typically

bull Battery-powered IoT devices are often small and servea particular function unlike server resources which havemassive calculation-driven platforms and consistent san-itized power flow

bull Asynchronous They are partially or completely offlineconnecting only asynchronously via hub devices or whenrequired for functionality

bull Lean Lastly IoT devices usually have limited calculationcapabilities and depend on central devices and servers forthis processing functionality

Despite all of these caveats IoT devices are desirable targets toattackers due to their known single-use functions and relativelylax security

Proof of Possession

Due to all of these caveats the OAuth workflow is strikinglydifferent mdash we are in fact using a methodology called Proofof Possession Consider a healthcare scenario in which a doctor

OAuth 20 ndash Why Itrsquos Vital to IoT Security 98

must access an EKG IoT device Since the IoT device cannotperform the same authentication process as a full client devicecan we need to do a bit of redirection

The start is normal The Client sends an access request to theAuthorization Server From here the Authorization Server con-tacts the Authentication Server which prompts the Client withAuthentication Data When this is provided the AuthenticationServer authenticates to the Authorization Server which issuesan authorization code to the Client

1 authorization_code = XYZ

From here we deviate from the standard OAuth workflow TheAuthorization code is a one-time use proof that the user is Au-thenticated and this code can be used to further contact thatIoT device as an authorized device The code is not somethingthat can be used to directly access data as other OAuth tokensare it is simply proof that we are who we say we are and thatwersquove been authenticated and authorized

The Client then generates a key (though this key can also begenerated server-side) to begin the connection process with theIoT device sending a packet of data that looks somewhat likethis

1 Client_id = device123

2 Client_secret = supersecret

3 Scope = read_ekg

4 Audience = ekg_device_ABC

5 authorization _code = XYZ

6 hellip

7 Key = a_shortlived_key

With the data in hand the Authorization Server now respondsto this packet by providing an access_token a reference to data

OAuth 20 ndash Why Itrsquos Vital to IoT Security 99

held in the Authorization Server memory to serve as proof ofpossession of both authentication and authorization

1 Access_token = oddfbmd-dnndjvhellip

This is the final step mdash the client is now fully and truly authen-ticated With this access_token the client can start a session onthe IoT device The IoT device will look at this access_token andpass it to the Authorization Server (if itrsquos a connected device)asking for verification to trust the device When the Authoriza-tionServer accepts the verification it passes anewkey to the IoTdevice which then returns it to the Client establishing a trustedconnection

Disconnected Flow

What happens if a device is unable to ask the AuthorizationServer for verificationdue topower or calculation limitations Inthis casewe can use something calledDisconnected Flow A keypoint for Disconnected Flow is unlike other OAuth 20 solutionsthis eschews TLS (Transport Layer Security) by nature of theResource Server being a disconnected device with intermittentconnectivity and limited communication and processing power

In this case wersquore actually shifting the parties around some-what The EKG machine is now the client and another IoT de-vice a test tube is the Resource Server First the EKG machineauthenticates and authorizes in the same way as before

OAuth 20 ndash Why Itrsquos Vital to IoT Security 100

1 Client_id = ekg_device_ABC

2 Client_secret = supersecret

3 Scope = read_result

4 Audience = connected_tbie_123

5 Token = original_token

6 hellip

7 Key = a_shortlived_key

Once the Authorization Server receives this the server repliesnot with the access token in the former structure but insteadan access_token in JWT (or JSON Web Token) This token is aby-value token meaning it contains the data fed to it and theresponseWhereas our first string referenced amemory locationin the Authorization Server the JWThas all of the data in a singlekey string

From here the JWT can be converted into other formats for eas-ier reading by the test tube By design the test tube is crafted totrust theAuthorizationServer inaprocesscalledPre-provisioningBecause of this whenwe send the Client token in JWT (or what-ever format thatrsquos been chosen) the tube implicitly trusts thekey as long as it originated from the Authorization Server andbegins a connected session with the Client

Ideskog notes therewould technically be 2 token types involvedin the flow above a signed JWT would contain an encryptedtoken (JWE) which has a key in it that is later used for thecommunication channel The JWS (commonly called JWT) isnrsquotnecessarily encrypted and is usually in plain text and signed

Real-World Authorization Failure

To see exactly why this is all so important consider some real-world authorization failures One of the most visible failures is

OAuth 20 ndash Why Itrsquos Vital to IoT Security 101

knownas ldquoTheSnappeningrdquo a leakof over 90000privatephotosand 9000 private videos from the Snapchat application

Most of the blame for The Snappening came from users us-ing unauthorized third-party applications to save Snaps Thesethird-party applications did not utilize OAuth solutions mean-ing when remote access users attempted to use the undocu-mented Snapchat URL that the third party application reliedon they could spoof as authorized users and retrieve contentwithout proper token assignment

This a great example of OAuth 20 vs no implementation as wehave essentially a ldquocontrolrdquo application (Snapchat secured byOAuth) and a ldquotestrdquo application (the unauthorized applicationstying into the undocumented API) With improper authorizationintegration the contentwasallowed to leak throughan insecuresystem with relative ease Had the third party application prop-erly implemented an authorization scheme this would neverhave happened

This issue is only relevant to non-IoT things though mdash itrsquos justa photo-sharing application right Wrong Consider now thissame fault of security for something like an IoT button thattriggers replacement business items Attacking this device canresult in man-in-the-middle attacks to capture addresses of or-der processing servers and even spoof orders to the tune ofthousands or hundreds of thousands of dollars

OAuth Embeds Trust into the IoT

Applying OAuth to the IoT makes it truly extensible and cus-tomizable Using OAuth we can build systems based on trustthat use fundamentally secure resources and communicationsprotocols OAuth is by design all about trust

This trust is key to securing the IoT For connected devices Proof

OAuth 20 ndash Why Itrsquos Vital to IoT Security 102

of Possession can solve most security issues For constrainedenvironments by either connectivity or processing calculativepower devices can be secured using pre-provisioning that isindependent of TLS and does not require the device to be onlineat all times

It should be noted that JWT JWS and JWE are all helpful toolsbut all work with JSON For lower processing environmentssibling binary tokens such as CWT CWS and CWE can be usedas they cater well to building on low power and limited scopedevices

Conclusion

This isnrsquot a gamemdashthoughhaving lax security canbeconvenientfor innovation and experimentation when it comes to the IoTthis is a dangerous approach IoT devices might be underpow-ered and single-use but they as a network are powerful

Remember that a network is only ever as secure as the sum ofits parts and the weakest point of entry to its ecosystem Failingto secure one IoT device and adopting a security system basedon inherited security can result in a single IoT device comprisingevery device connected to it

OAuth 20 can go a long way towards solving these issues

Is OAuth Enough forFinancial-Grade APISecurityby Art AnthonyOriginally Published Here

ldquoIf you think about where OAuth [and OpenID Connect] startedit was really about securing comments on blog posts and nowwersquore talking about enterprises so itrsquos a whole different class ofsecurityrdquo

This is how Travis Spencer CEO at the identity company Curityopened his talk at our 2019 Austin API Summit and itrsquos an astutesummary of the way many products (particularly in the techscene) are tweaked or re-engineered for new things differentfrom their original purpose

Is OAuth Enough for Financial-Grade API Security 104

As Spencer clarified in his talk ldquowhen we say banking gradewersquore not just talking about banks wersquore talking about health-care government and high securityrdquo In other words financialgrade security is relevant to any data-centric API

Itrsquos often true that products that begin their life as one thingstruggle to adapt to new tasks because they are not originallydesigned for In this postwersquoll be looking atwhether or not thatrsquosthe case here ie how the likes of OAuth have evolved fromhumble beginnings and if theyrsquore truly capable of being used forfinancial grade protection

Can OAuth Make The Grade

Early in his talk Spencer provides a summary of some thingsyou candowith yourOAuth implementation toprovide financialgrade security

bull Mutual TLS constrained tokensbull PKCE (Proof Key for Code Exchange)bull Consentbull Signed requestresponse objectsbull Pairwise Pseudonymous Identifiers (PPIDs)bull Phantom tokensbull Strong authenticationbull Prefix scopesbull Dynamic clients

Therersquos no denying thatrsquos a pretty comprehensive list and sug-gests that OAuth is more than capable of holding its own whenit comes to security

In other words OAuth shouldnrsquot be seen as insufficient when itcomes to securing data In fact Spencer outlines a number ofways in which it works very well for financial grade protection

Is OAuth Enough for Financial-Grade API Security 105

For example he talks about how PPIDs can be used to preventcollusion between unrelated apps ndash while allowing interactionbetween say sites and their associated mobile apps ndash and howphantom tokens (vs say a JSONweb token) allow for a smallerregulated space while preventing clients from accessing any PIIand front-end clients from depending on the content of accesstokens

Some Tokens Are Unbearer-able

Thewaydevelopers useOAuth isnrsquot however always perfect Itstwo main vulnerabilities of OAuth as seen by Spencer Bearertokens and the redirect ldquoThose two things are the primary at-tack vectors in OAuthrdquo

He likens the former to bearer bonds ldquoif you bear the bondthenhellipyou can get a million dollars for each piece of paper andhave a great liferdquo Thatrsquos particularly problematic here becauseunlike with bearer bonds therersquos no way to lock tokens away ina physical safe

ldquoThatrsquos the Achilles heel because if I can snatch someone elsersquostoken I can become themrdquo So whatrsquos a solution that can getaround this ldquoThe opposite of this is a holder of key token orproof of possession token and thatrsquos what mutual TLS con-straint tokens arerdquo

Is OAuth Enough for Financial-Grade API Security 106

In simple terms the addition of a hash of a certificate to thetoken exchange process means that works something like usinga cipher to decode a message without the proper credentialsthe token wonrsquot function properly when used for an API call

Unfortunately that isnrsquot the end of the storyhellip

AwayWith The PKCEs

When talking about redirects Spencer refers to the vulnerabilityin callbacks that exists ifhellip

bull Itrsquos not confidential ie not done over TLSbull Therersquos no authentication done on the token endpointbull The callback is not unique per client or per client operator

ldquoIn cases where a bad actor can intercept the credentials theymay be able to sidestep the use of mutual TLS tokens outlinedabove entirelyrdquo He also highlights that this is something partic-ularly prevalent in mobile devices

Is OAuth Enough for Financial-Grade API Security 107

The solution Proof Keys for Code Exchange (PKCE) ldquoWe canadd a step 0 into this processhellipThe legitimate application usesa proof key to prove that it is the actual application that startedthis flow with the OAuth server refusing to finish it unless thatproof is verifiedrdquo

Youcould thinkof this asamore robust versionofDennisNedryrsquosldquoah ah ah you didnrsquot say the magic wordrdquo in Jurassic Parkhellip

Signed Sealed Delivered

Spencer highlights the issue that in most cases OAuth flowsgo through the user agent Malware installed in the browser forexample can undermine all of themeasures taken above on theuser side

ldquoHowdowe know that OAuth flows arenrsquot being tam-pered with in flightrdquo Spencer asks ldquoWe sign the re-quest fromtheclient sent to the server andbackhellipWecan also sign the response thatrsquos sent back to theclient as well so they know nothing was tamperedwith on the way backrdquo

All of this signingandhashing is something thatrsquos alreadyprovenits worth in recent years read any article about data leaks by bigcompanies and yoursquoll notice in caseswhere itrsquos beendone howeager they are to talk about hashing passwords

Although hashing passwords signing requests etc isnrsquot always100 secure mdash there are cases for example in which weakhashing has been crackedmdash it is at this point in time about thebest thing we can do

Is OAuth Enough for Financial-Grade API Security 108

Whatrsquos Next For Financial Grade APISecurity

It seems likely for now at least that the status quowill continueas the norm in the world of financial and financial grade APIs

From PayPal and Stripe to Coinbase and probably FacebookrsquosLibra in the not too distant future there are plenty of financialservices utilizing APIs built around existing frameworks and ser-vices like OAuth

Suppose actual financial services are already relyingon these Inthat case therersquos very little incentive for other API developers togobeyondwhat already in effect constitutes financial gradeAPIsecurityhellipbarringmassivedata leaksor theexpositionof seriousvulnerabilities

In the meantime we would expect to see OAuth continue tobe one of those rare exceptions a service that was built withsomethingminor ie securing blog comments inmind that haseffectively expanded to somethingmuchmore robust than that

The Role of Identity in APISecurityby Bill DoerrfeldOriginally Published Here

What options do APIs and microservices have when it comes toauthentication and authorization What is the role of identity inAPI security In a recent LiveCast we sought to discover bestpractices for handling identity within API security We featuredtwo illuminating lightning talks one from David Garney of Tykand another from Travis Spencer of Curity This event is a nicecapstone to the API security and identity themes wersquove coveredin this eBook

The Role of Identity in API Security 110

Various Authentication Mechanisms

So how do we authenticate users for our APIs Embedded intothird-party applications APIs require a unique type of accesscontrol and there are many options for microservices authen-tication and authorization

The Benefits of Microservices

As wersquove seen before microservices are lightweight offering in-dividualistic simplicity that monolith applications simply canrsquotprovide They are also flexible services can be deployed to dif-ferent hosts and with varying technical stacks They work wellwith containerization CI and CD Furthermore since these ap-plications are separated it means the attack exposure is de-creased increasing security overall

Though microservices are unique they often work in tandemwith one anothermeaningwe need them to act cohesively Oneexample is having a standard way of knowingwho is consumingthem and their access privileges

So howdowe implement a standard authentication and autho-rization method across all microservices In his presentationDave Garney of Tyke cites three specific ways to implement thiscontrol

1 Internally within eachmicroservice2 Externally by using a gateway3 Or using a combination of external and internal compo-

nents

The Role of Identity in API Security 111

Internal Approach

In the 100 internal strategy microservices handle both au-thentication and authorization In this architecture the user tra-verses through both Thus the service has fine-grained controlbut it also means that the service is self-reliant fitting with themicroservices approach Cons include extra development effortand likelyadditionalmicroservicesmustbebeingconstructed tohandle these functions

Dave argues that by handling authentication and authorizationseparately for each microservice wersquore missing an opportunityto reduce code bloat The larger the number of microservicesinvolved the more value in externalizing this approach

External

With an external approach a gateway handles both authenti-cation and authorization Thus additional microservices do notneed to be created The pros are that by putting responsibility inthe gateway you can remove the burden frommicroservices tofocus on your own needs The cons could be less fine-grainedcontrol if the gateway canrsquot make decisions on information itdoesnrsquot have access to Dave also notes some potential vul-nerabilities relying completely on a gateway means you couldattempt to circumnavigate it and access the source directly Ofcourse there are ways to mitigate this

Combination

In Daversquos combination approach authentication takes place inthe gateway as the external approach thus relieving the bur-

The Role of Identity in API Security 112

den for each microservice to handle authentication Authoriza-tion takes place in themicroservice Microservices thus becomeleaner as they donrsquotrsquo have to worry about authentication yetthey can still authorize based on the credentials provided Conscould be a little bit more development effort

Goldilocks Approach

Dave recommends the external approach if possible as allow-ing a gateway to handle both authorization and authenticationbrings time-saving qualities He notes that practicallymostwilluse a Goldilocks approach a middle ground between combina-tion and external approaches

ldquoTry to identify complex authorization requirementsand implement them in your microservicerdquo

Dave defines this way of thinking as Macro-authorization vsMicro-authorizationMacro-authorization as in the gateway au-thorizingaccess toall of yourmicroservicesandMicro-authorizationaseachmicroserviceproviding furtherauthorization themselvesHe recommends complex authorization mechanics catered tothe unique scenarios at hand Database access for example isbest implemented as micro-authorization

Dave recommends OpenID Connect for authentication and forthe most part stresses the importance of gateways for offload-ing functionality to the gateway

ldquoWhat you should end up with is the right balanceof off-loading asmuch authentication and authoriza-tion effort to the gateway as possible while retainingthe ability to perform complex authorization at themicroservice levelrdquo

The Role of Identity in API Security 113

Moving Forward with OAuth and OpenIDConnect

Next letrsquos dig into OAuth and OpenID Connect a bit more TravisSpencer CEO of Curity is no stranger to strategies for identitycontrol He describes Curity as an advanced off-the-shelf OAuthserver fit for banking retail telecom andmany other use cases

The 4 Actors of OAuth

Travis defines the basic foundations of OAuthwith these four ac-tors This is what the literature and documentation concerningOAuth will often use These four actors make up the flows thatwe discuss on the blog often

1 Client The application can be mobile apps web appsserver applications andmore

2 AuthorizationServer (OAuthServer) Sometimescalled iden-tity provider or in OpenID Connect itrsquos called the OP

3 Resource Server These are the APIs themselves4 ResourceOwner Typically auser theone that controls the

resource Could also be anorganization but is often a user

So how do these actors typically interact Well for more fine-grained comparisons reference Part 2 of this eBook for specificOAuth flows

Nordic APIs ResourcesRelated API Security and Identity Sessions

bull OAuth Assisted Token Flow for Single Page Applicationsbull OAuth Claims Ontology Using Claims in OAuth and HowThey Relate to Scopes

bull OAuth for Your Living Roombull Jacob Has a Horse Says Travis ndash a Tale of Truths In aMicroservice Architecture

bull IdentityThe Missing Link in API securitybull Lessons Learned from the Design of the SCIM APIbull LiveCast The Role Of Identity In API Security

Visit our YoutubeChannel for other full videos of high impact APIand identity-related talks

More eBooks by Nordic APIs

Visit our eBook page to download all the following eBooks forfree

API Strategy for Open Banking Banking infrastructure is de-composing into reusable API-first components Discover theAPIside of open banking with best practices and case studies fromsome of the worldacirceurotrades leading open banking initiatives

GraphQL or Bust Everything GraphQL Explore the benefits ofGraphQL differences between it and REST nuanced securityconcerns extending GraphQL with additional tooling GraphQL-specific consoles andmore

Nordic APIs Resources 115

How to Successfully Market an API The bible for project man-agers technical evangelists or marketing aficionados in theprocess of promoting an API program

The API Economy APIs have given birth to a variety of unprece-dented services Learn how to get the most out of this neweconomy

APIDriven-DevOpsOne importantdevelopment in recentyearshas been the emergence of DevOps a discipline at the cross-roads between application development and system adminis-tration

Securing the API Stronghold The most comprehensive freelyavailable deep dive into the core tenants of modern web APIsecurity identity control and access management

Developing The APIMindset Distinguishes Public Private andPartner API business strategies with use cases from Nordic APIsevents

Create With Us

At Nordic APIs we are striving to inspire API practitioners withthought-provoking content By sharing compelling stories weaim to show that everyone can benefit from using APIs

Write Our blog is open for submissions from the community Ifyou have an API story to share please read our guidelines andpitch a topic here

Speak If you would like to speak at a future Nordic APIs eventplease visit our call for speakers page

Nordic APIs Resources 116

About Nordic APIs

Nordic APIs is an independent blog and this publication has notbeen authorized sponsored or otherwise approved by any com-pany mentioned in it All trademarks servicemarks registeredtrademarks and registered servicemarks are the property of theirrespective owners

Nordic APIs AB copy

Facebook | Twitter | Linkedin | YouTube

Blog | Home | Newsletter

  • Table of Contents
  • Foreword
  • Preface
  • Part One Basic Identity Concepts
    • Introducing The API Security Maturity Model
    • The Difference Between HTTP Auth API Keys and OAuth
    • API Keys ne Security Why API Keys Are Not Enough
    • Why Canrsquot I Just Send JWTs Without OAuth
    • How To Control User Identity Within Microservices
      • Part Two OAuth Flows and Deep Dives
        • 8 Types of OAuth Flows And Powers
        • Exploring OAuthtools The Worlds First OAuth Playground
        • Strategies for integrating OAuth with API Gateways
        • Assisted Token Flow The Answer to OAuth Integration in Single Page Applications
        • Using OAuth Device Flow For UI-Incapable Devices
        • SCIM Building the Identity Layer for the Internet
          • Part Three The Role of Identity
            • OAuth 20 ndash Why Its Vital to IoT Security
            • Is OAuth Enough for Financial-Grade API Security
            • The Role of Identity in API Security
              • Nordic APIs Resources