Anda di halaman 1dari 121

Oracle Fusion Middleware

OracleAPIGatewayOAuthUserGuide
11gRelease2(11.1.2.4.0)

July2015

OracleAPIGatewayOAuthUserGuide,11gRelease2(11.1.2.4.0)

Copyright1999,2015,Oracleand/oritsaffiliates.Allrightsreserved.

Thissoftwareandrelateddocumentationareprovidedunderalicenseagreementcontainingrestrictionsonuseand
disclosureandareprotectedbyintellectualpropertylaws.Exceptasexpresslypermittedinyourlicenseagreementorallowed
bylaw,youmaynotuse,copy,reproduce,translate,broadcast,modify,license,transmit,distribute,exhibit,perform,
publish,ordisplayanypart,inanyform,orbyanymeans.Reverseengineering,disassembly,ordecompilationofthis
software,unlessrequiredbylawforinteroperability,isprohibited.

Theinformationcontainedhereinissubjecttochangewithoutnoticeandisnotwarrantedtobeerror-free.Ifyoufindany
errors,pleasereportthemtousinwriting.

IfthissoftwareorrelateddocumentationisdeliveredtotheU.S.GovernmentoranyonelicensingitonbehalfoftheU.S.
Government,thefollowingnoticeisapplicable:

U.S.GOVERNMENTRIGHTSPrograms,software,databases,andrelateddocumentationandtechnicaldatadeliveredtoU.S.
Governmentcustomersare"commercialcomputersoftware"or"commercialtechnicaldata"pursuanttotheapplicable
FederalAcquisitionRegulationandagency-specificsupplementalregulations.Assuch,theuse,duplication,disclosure,
modification,andadaptationshallbesubjecttotherestrictionsandlicensetermssetforthintheapplicableGovernment
contract,and,totheextentapplicablebythetermsoftheGovernmentcontract,theadditionalrightssetforthinFAR52.227-
19,CommercialComputerSoftwareLicense(December2007).OracleUSA,Inc.,500OracleParkway,RedwoodCity,CA
94065.

Thissoftwareisdevelopedforgeneraluseinavarietyofinformationmanagementapplications.Itisnotdevelopedor
intendedforuseinanyinherentlydangerousapplications,includingapplicationswhichmaycreateariskofpersonalinjury.If
youusethissoftwareindangerousapplications,thenyoushallberesponsibletotakeallappropriatefail-safe,backup,
redundancy,andothermeasurestoensurethesafeuseofthissoftware.OracleCorporationanditsaffiliatesdisclaimany
liabilityforanydamagescausedbyuseofthissoftwareindangerousapplications.

OracleisaregisteredtrademarkofOracleCorporationand/oritsaffiliates.Othernamesmaybetrademarksoftheirrespective
owners.

Thissoftwareanddocumentationmayprovideaccesstoorinformationoncontent,products,andservicesfromthirdparties.
OracleCorporationanditsaffiliatesarenotresponsibleforandexpresslydisclaimallwarrantiesofanykindwithrespectto
third-partycontent,products,andservices.OracleCorporationanditsaffiliateswillnotberesponsibleforanyloss,costs,or
damagesincurredduetoyouraccesstooruseofthird-partycontent,products,orservices.Thisdocumentationisin
prereleasestatusandisintendedfordemonstrationandpreliminaryuseonly.Itmaynotbespecifictothehardwareonwhich
youareusingthesoftware.OracleCorporationanditsaffiliatesarenotresponsibleforandexpresslydisclaimallwarrantiesof
anykindwithrespecttothisdocumentationandwillnotberesponsibleforanyloss,costs,ordamagesincurredduetothe
useofthisdocumentation.

Theinformationcontainedinthisdocumentisforinformationalsharingpurposesonlyandshouldbeconsideredinyour
capacityasacustomeradvisoryboardmemberorpursuanttoyourbetatrialagreementonly.Itisnotacommitmentto
deliveranymaterial,code,orfunctionality,andshouldnotberelieduponinmakingpurchasingdecisions.Thedevelopment,
release,andtimingofanyfeaturesorfunctionalitydescribedinthisdocumentremainsatthesolediscretionofOracle.

Thisdocumentinanyform,softwareorprintedmatter,containsproprietaryinformationthatistheexclusivepropertyof
Oracle.YouraccesstoanduseofthisconfidentialmaterialissubjecttothetermsandconditionsofyourOracleSoftware
LicenseandServiceAgreement,whichhasbeenexecutedandwithwhichyouagreetocomply.Thisdocumentand
informationcontainedhereinmaynotbedisclosed,copied,reproduced,ordistributedtoanyoneoutsideOraclewithout
priorwrittenconsentofOracle.Thisdocumentisnotpartofyourlicenseagreementnorcanitbeincorporatedintoany
contractualagreementwithOracleoritssubsidiariesoraffiliates.

27July2015
Contents

Preface 8
Whoshouldreadthisdocument 8
Howtousethisdocument 8

What's new 10

1 OAuth and OpenID Connect concepts 11


OAuth2.0 11
OpenIDConnect1.0 12

2 Introduction to API Gateway OAuth 2.0 server 13


APIGatewayOAuthconcepts 13
OAuthserverexampleworkflow 14
APIGatewayOAuthserverfeatures 15
Furtherinformation 16

3 API Gateway OAuth 2.0 authentication flows 17


Runthesamplescripts 18
Authorizationcodegrant(orwebserver)flow 18
Obtainanaccesstoken 19
Runthesampleclient 22
Furtherinformation 24
Implicitgrant(oruseragent)flow 24
Obtainanaccesstoken 25
Runthesampleclient 27
Furtherinformation 28
Resourceownerpasswordcredentialsflow 29
Requestanaccesstoken 29
Handletheresponse 30
Runthesampleclient 30
Furtherinformation 31
Clientcredentialsgrantflow 31
Requestanaccesstoken 32
Handletheresponse 32
Runthesampleclient 33
Furtherinformation 33
JWTflow 33
CreateaJWTbearertoken 34
Requestanaccesstoken 36

Oracle API Gateway11.1.2.4.0 OAuth User Guide3


Handletheresponse 36
Runthesampleclient 37
Furtherinformation 37
Revoketoken 37
Runthesampleclient 38
Responsecodes 39
Furtherinformation 39
Tokeninformationservice 39
Runthesampleclient 40
Responsecodes 41
Furtherinformation 42

4 Set up API Gateway as an OAuth 2.0 server 43


EnableOAuthmanagement 43
EnableOAuthendpoints 45
Importsampleclientapplications 45
Migrateexistingclientapplications 46

5 API Gateway as an OAuth 2.0 authorization server 48


Manageaccesstokensandauthorizationcodes 48

6 OAuth 2.0 authorization server filters 51


Getaccesstokeninformation 52
Overview 52
Tokensettings 52
Monitoringsettings 52
Advancedsettings 53
Getaccesstokenusingauthorizationcode 53
Overview 53
Applicationvalidationsettings 54
Accesstokensettings 54
Monitoringsettings 55
Getaccesstokenusingclientcredentials 55
Overview 55
Applicationvalidationsettings 56
Accesstokensettings 56
Monitoringsettings 57
GetaccesstokenusingJWT 58
Overview 58
Applicationvalidationsettings 58
Accesstokensettings 59
Monitoringsettings 60
GetaccesstokenusingSAMLassertion 61
Overview 61

Oracle API Gateway11.1.2.4.0 OAuth User Guide4


SAMLassertionvalidationsettings 61
Accesstokensettings 62
Monitoringsettings 63
Consumeauthorizationrequests 64
Overview 64
Validationsettings 64
Authorizationcodesettings 65
Accesstokensettings 66
Advancedsettings 67
Refreshaccesstoken 68
Overview 68
Applicationvalidationsettings 68
Accesstokensettings 68
Monitoringsettings 69
Getaccesstokenusingresourceownercredentials 70
Overview 70
Applicationvalidationsettings 70
Accesstokensettings 71
Monitoringsettings 72
Revoketoken 73
Overview 73
Revoketokensettings 73
Monitoringsettings 74

7 API Gateway as an OAuth 2.0 resource server 75


RegisterandmanageOAuthclientapplications 75
Manageclientapplications 75
ManageOAuthscopes 76
ClientApplicationRegistry 78

8 OAuth 2.0 resource server filters 80


Validateaccesstoken 80
Overview 80
Generalsettings 80
Responsecodes 81

9 API Gateway as an OAuth 2.0 client 83


IntroductiontoAPIGatewayOAuthclient 83
APIGatewayOAuthclientfeatures 84
OAuth2.0exampleclientworkflow 85
SetupAPIGatewayOAuthclient 86
ConfigureOAuthclientapplicationcredentials 86
Addapplicationcredentials 87
AddOAuthprovider 91

Oracle API Gateway11.1.2.4.0 OAuth User Guide5


CreateacallbackURLlistener 91
Manageclientaccesstokens 91

10 OAuth 2.0 client filters 93


DeleteanOAuthclientaccesstoken 93
Overview 93
Generalsettings 94
GetOAuthclientaccesstoken 94
Overview 94
Generalsettings 94
SSLsettings 94
Additionalsettings 95
Redirectresourceownertoauthorizationserver 95
Overview 95
Generalsettings 95
RefreshanOAuthclientaccesstoken 96
Overview 96
Generalsettings 96
SSLsettings 97
Additionalsettings 97
RetrieveOAuthclientaccesstokenfromtokenstorage 97
Overview 97
Generalsettings 98
SaveanOAuthclientaccesstoken 98
Overview 98
Generalsettings 98

11 API Gateway and OpenID Connect 100


IntroductiontoAPIGatewayOpenIDConnect 100
OpenIDConnectconcepts 101
RelationshiptoOAuth2.0 101
Prerequisites 103
OpenIDConnectflow 104
BuildanOpenIDConnectIdPserver 105
BuildanOpenIDConnectclient 105
UsetheAPIGatewayOAuthclientdemo 106
Deploytheclientdemo 108
Clientpolicies 108

12 OpenID Connect filters 110


CreateanOpenIDConnectIDtoken 110
Overview 110
Generalsettings 111
VerifyanOpenIDConnectIDtoken 111

Oracle API Gateway11.1.2.4.0 OAuth User Guide6


Overview 111
Generalsettings 112

Appendix A: OAuth 2.0 message attributes 113


OAuth2.0servermessageattributes 113
accesstokenmethods 113
accesstoken.authnmethods 114
authzcodemethods 114
oauth.client.detailsmethods 115
Exampleofqueryingamessageattribute 116
OAuthscopeattributes 118
OAuthSAMLbearerattributes 119
OAuth2.0clientmessageattributes 119
oauth.client.accesstokenmethods 119
oauth.client.applicationmethods 120

Oracle API Gateway11.1.2.4.0 OAuth User Guide7


Preface

ThisdocumentdescribeshowtousetheOAuth2.0andOpenIDConnectfeaturesofAPIGateway.It
describeshowtoconfigureAPIGatewayasanOAuthserverandasanOAuthclient.Italsodescribes
theOpenIDConnectsupportprovidedbyAPIGateway.

Who should read this document


Theintendedaudienceforthisdocumentispolicydevelopersandsystemintegratorswhoare
responsibleforconfiguringOAuthandOpenIDConnectflows.

BeforeconfiguringOAuthorOpenIDConnectflowsinAPIGatewayyoushouldunderstandexactly
whatmessagefiltersare,andhowtheyarechainedtogethertocreateamessagepolicy.These
conceptsaredocumentedindetailintheAPIGatewayPolicyDeveloperGuide.Youshouldalsohave
anunderstandingofAPIGatewayconceptsandfeatures.Formoreinformation,seetheAPIGateway
ConceptsGuide.

How to use this document


ThisdocumentshouldbeusedinconjunctionwiththeotherdocumentsintheAPIGateway
documentationset.

BeforeyoubeginusingtheOAuthfeaturesofAPIGateway,reviewthisdocumentthoroughly.The
followingisabriefdescriptionofthecontentsofeachchapter:

OAuthandOpenIDConnectconceptsonpage11DescribesOAuth2.0andOpenIDConnect
concepts.

IntroductiontoAPIGatewayOAuth2.0serveronpage13DescribesthefeaturesofAPIGateway
asanOAuthserver.

APIGatewayOAuth2.0authenticationflowsonpage17DescribestheOAuthflowssupportedby
APIGateway.

SetupAPIGatewayasanOAuth2.0serveronpage43DescribeshowtosetupAPIGatewayasan
OAuthserver.

APIGatewayasanOAuth2.0authorizationserveronpage48DescribestheOAuthauthorization
serverfeaturesofAPIGateway.

OAuth2.0authorizationserverfiltersonpage51DescribeshowtoconfiguretheOAuth
authorizationserverfilters.

APIGatewayasanOAuth2.0resourceserveronpage75DescribestheOAuthresourceserver
featuresofAPIGateway.

Oracle API Gateway11.1.2.4.0 OAuth User Guide8


Preface

OAuth2.0resourceserverfiltersonpage80DescribeshowtoconfiguretheOAuthresourceserver
filters.

APIGatewayasanOAuth2.0clientonpage83DescribestheOAuthclientfeaturesofAPI
Gateway.

OAuth2.0clientfiltersonpage93DescribeshowtoconfiguretheOAuthclientfilters.

APIGatewayandOpenIDConnectonpage100DescribeshowtousetheOpenIDConnectfeatures
ofAPIGateway.

OpenIDConnectfiltersonpage110DescribeshowtoconfiguretheOpenIDConnectfilters.

OAuth2.0messageattributesonpage113DescribesthemessageattributesusedintheOAuth
filters.

Oracle API Gateway11.1.2.4.0 OAuth User Guide9


What's new

ThisreleaseoftheAPIGatewayOAuthUserGuidecontainsthefollowingchanges:
l NewconceptssectionSeeOAuthandOpenIDConnectconceptsonpage11.
l NewsectiononOpenIDConnectfeaturesSeeAPIGatewayandOpenIDConnectonpage100.
l RestructuringofthesectiononAPIGatewayasanOAuthserverintotwoparts:
o APIGatewayasanOAuth2.0authorizationserveronpage48
o APIGatewayasanOAuth2.0resourceserveronpage75
l ChangestotheOAuthauthorizationserverfilterssectionTheAuthorize Transactionfilter
hasbeenremovedandthefunctionalitymovedtotheAuthorization Code Flowfilter.See
Consumeauthorizationrequestsonpage64
l ChangestotheOAuthclientfilterssectionTheRedirect resource owner to Authz Server
andGet OAuth Access Tokenfiltershavebeenmodified.SeeRedirectresourceownerto
authorizationserveronpage95andGetOAuthclientaccesstokenonpage94.
l ChangestothemonitoringsettingsinallOAuthserverfilters.
l ThesectiononOAuthmessageattributeshasbeenmovedtoanappendix.SeeOAuth2.0
messageattributesonpage113.
l Thedefaultusernamesandpasswordshavebeenremovedfromalldocumentationforsecurity
reasons.YoucanobtainthedefaultusernamesandpasswordsfromyourOracleAccount
Manager.

Oracle API Gateway11.1.2.4.0 OAuth User Guide10


OAuth and OpenID
Connect concepts 1
OAuth2.0isadelegationprotocolthatisusefulforconveyingauthorizationdecisionsacrossa
networkofweb-enabledapplicationsandAPIs.OAuth2.0isnotanauthenticationprotocol,
however,OpenIDConnectcanbeusedalongwithOAuthtocreateanauthenticationandidentity
protocolontopofthisdelegationandauthorizationprotocol.

OAuth 2.0
OAuth2.0isspecifiedintheOAuth2.0AuthorizationFramework.OAuthcanbeusedtoprovide:

l Delegatedaccess
l Reductionofpasswordsharingbetweenusersandthird-parties
l Revocationofaccess
Forexample,whenuserssharetheircredentialswithathird-partyapplication,theonlywayto
revokeaccessfromthatapplicationisfortheusertochangetheirpassword.However,thismeans
thataccessfromallotherapplicationsisalsorevoked.WithOAuth,userscanrevokeaccessfrom
specificapplicationswithoutbreakingotherapplicationsthatshouldbeallowedtocontinuetoact
ontheirbehalf.

OAuthachievesthisbyintroducinganauthorizationlayerandseparatingtheroleoftheclientfrom
thatoftheresourceowner.OAuthdefinesfourprimaryroles:

l Resourceowner(RO):TheentitythatisincontrolofthedataexposedbyanAPI(forexample,
anenduser).

l Client:Themobileapplication,website,andsoon,thatwantstoaccessdataonbehalfofthe
resourceowner.
l Authorizationserver(AS):TheSecurityTokenService(STS)orOAuthserverthatissuestokens.
l Resourceserver(RS):Theservicethatexposesthedata(forexample,anAPI).
Theclientrequestsaccesstoresourcescontrolledbytheresourceownerandhostedbytheresource
server,andisissuedadifferentsetofcredentialsthanthoseoftheresourceowner.Insteadofusing
theresourceowner'scredentialstoaccessprotectedresources,theclientobtainsanaccesstoken-a
stringdenotingaspecificscope,lifetime,andsoon.Accesstokensareissuedtothird-partyclients
byanauthorizationserverwiththeapprovaloftheresourceowner.Theclientusestheaccesstoken
toaccesstheprotectedresourceshostedbytheresourceserver.

OAuthdefinestwokindsoftokens:

l Accesstokens:Thesetokensarepresentedbyaclienttotheresourceserver(forexample,an
API),togetaccesstoaprotectedresource.

Oracle API Gateway11.1.2.4.0 OAuth User Guide11


1 OAuth and OpenID Connect concepts

l Refreshtokens:Theseareusedbytheclienttogetanewaccesstokenfromtheauthorization
server(forexample,whentheaccesstokenexpires).
OAuthtokenscanincludeascope.Scopesarelikepermissionsorrightsthataresourceowner
delegatestoaclient,sothattheycanperformcertainactionsontheirbehalf.Aclientcanrequest
specificrights,butausermightonlygrantasubset,ormightgrantothersthatwerenotrequested.
TheOAuthspecificationdoesnotdefinespecificscopes,meaningthatyoucanuseanystringto
representanOAuthscope.

OAuthdefinesseveraldifferentflowsormessageexchangepatterns.Themostcommonlyusedisthe
authorizationcode(webserver)flow.FormoredetailsonthisflowandtheotherflowsthatAPI
Gatewaysupports,seeAPIGatewayOAuth2.0authenticationflowsonpage17.

OpenID Connect 1.0


OpenIDConnectisspecifiedintheOpenIDConnect1.0specification.OpenIDConnectbuildsonthe
OAuthprotocolanddefinesaninteroperablewaytouseOAuth2.0toperformuserauthentication.
OpenIDConnect1.0isasimpleidentitylayerontopoftheOAuth2.0protocol.Itenablesclientsto
verifytheidentityoftheuserbasedontheauthenticationperformedbyanauthorizationserver,as
wellastoobtainbasicprofileinformationabouttheuser.

OpenIDConnectdefinesthefollowingroles:

l Relyingparty(RP):AnOAuthclientthatsupportsOpenIDConnect.Themobileapplication,web
site,andsoon,thatwantstoaccessdataonbehalfoftheresourceowner.

l OpenIDprovider(OP):AnOAuthauthorizationserverthatiscapableofauthenticatingtheuser
andprovidingclaimstoarelyingpartyabouttheauthenticationeventandtheuser.
OpenIDConnectdefinesanewkindoftoken,theIDtoken.TheOpenIDConnectIDtokenisa
signedJSONWebToken(JWT)thatisgiventotheclientapplicationalongsidetheregularOAuth
accesstoken.TheIDtokencontainsasetofclaimsabouttheauthenticationsession,includingan
identifierfortheuser(sub),anidentifierforissuerofthetoken(iss),andtheidentifierofthe
clientforwhichthistokenwascreated(aud).SincetheformatoftheIDtokenisknownbythe
client,itcanparsethecontentofthetokendirectly.

InadditiontotheclaimsintheIDtoken,OpenIDConnectdefinesastandardprotectedresource
(theUserInfoendpoint)thatcontainsclaimsaboutthecurrentuser.OpenIDConnectdefinesaset
ofstandardizedOAuthscopesthatmaptoclaims(profile,email,phone,andaddress).Ifthe
enduserauthorizestheclienttoaccessthesescopes,theOPreleasestheassociateddata( claims)to
theclientwhentheclientcallstheUserInfoendpoint.OpenIDConnectalsodefinesaspecial
openidscopethatswitchestheOAuthserverintoOpenIDConnectmode.

Oracle API Gateway11.1.2.4.0 OAuth User Guide12


Introduction to API
Gateway OAuth 2.0 server 2
OAuth2.0isanopenstandardforauthorizationthatenablesclientapplicationstoaccessserver
resourcesonbehalfofaspecificresourceowner.OAuthalsoenablesresourceowners(endusers)to
authorizelimitedthird-partyaccesstotheirserverresourceswithoutsharingtheircredentials.For
example,aGmailusercouldallowLinkedInorFlickrtohaveaccesstotheirlistofcontactswithout
sharingtheirGmailusernameandpassword.

TheAPIGatewaycanbeusedasanauthorizationserverandasaresourceserver.Anauthorization
serverissuestokenstoclientapplicationsonbehalfofaresourceownerforuseinauthenticating
subsequentAPIcallstotheresourceserver.Theresourceserverhoststheprotectedresources,and
canacceptorrespondtoprotectedresourcerequestsusingaccesstokens.

Note Thisguideassumesthatyouarefamiliarwiththetermsandconceptsdescribedinthe
OAuth2.0AuthorizationFramework.

API Gateway OAuth concepts


TheAPIGatewayusesthefollowingdefinitionsofbasicOAuth2.0terms:

l Resourceowner Anentitycapableofgrantingaccesstoaprotectedresource.Whenthe
resourceownerisaperson,itisreferredtoasanenduser.
l ResourceserverTheserverhostingtheprotectedresources,andwhichiscapableofaccepting
andrespondingtoprotectedresourcerequestsusingaccesstokens.Inthiscase,theAPI
Gatewayactsasagatewayimplementingtheresourceserverthatsitsinfrontoftheprotected
resources.

l ClientapplicationAclientapplicationmakingprotectedrequestsonbehalfoftheresource
ownerandwithitsauthorization.
l AuthorizationserverTheserverissuingaccesstokenstotheclientapplicationaftersuccessfully
authenticatingtheresourceownerandobtainingauthorization.Inthiscase,theAPIGateway
actsbothastheauthorizationserverandastheresourceserver.
l ScopeUsedtocontrolaccesstotheresourceowner'sdatawhenrequestedbyaclient
application.YoucanvalidatetheOAuthscopesintheincomingmessageagainstthescopes
registeredintheAPIGateway.Anexamplescopeisuserinfo/readonly.

Oracle API Gateway11.1.2.4.0 OAuth User Guide13


2 Introduction to API Gateway OAuth 2.0 server

OAuth server example workflow


AssumethatyouareusingaimageprintingwebsitesuchasCanontoprintsomeofyourphotos.
YoualsohavesomephotosonyourFlickraccountthatyouwouldliketoprint.However,youmust
downloadalltheselocally,andthenuploadthemagaintotheprintingwebsite,whichis
inconvenient.YouwouldliketobeabletosignintoFlickrfromyourCanonprintingprofile,and
printyourphotosdirectly.

ThisproblemcanbesolvedusingtheexampleOAuth2.0webserverflowshowninthefollowing
diagram:

Outofband,theCanonprintingclientapplicationpreregisterswithFlickrandobtainsaclientIDand
secret.TheclientapplicationregistersacallbackURLtoreceivetheauthorizationcodefromFlickr
whenyou,asresourceowner,allowCanontoaccessthephotosfromFlickr.Theprinting
applicationhasalsorequestedaccesstoanAPInamed/flickr/photos,whichhasanOAuth
scopeofphotos.

Thestepsinthediagramaredescribedasfollows:

1. YouareusingamobilephoneandaresignedintotheCanonimageprintingwebsite.Youclick
toprintFlickrphotos.TheCanonclientapplicationredirectsyoutotheFlickrOAuth
authorizationserver.YoumustalreadyhaveaFlickraccount.

Oracle API Gateway11.1.2.4.0 OAuth User Guide14


2 Introduction to API Gateway OAuth 2.0 server

2. YoulogintoyourFlickraccount,andtheFlickrauthorizationserverasksyou"Doyouwantto
allowtheCanonprintingapplicationtoaccessyourphotos?"YouclickYestoauthorize.
3. Whensuccessful,theprintingapplicationreceivesanauthorizationcodeatthecallbackURL
thatwaspreregisteredoutofband.
Note YouhavenotsharedyourFlickrusernameandpasswordwiththeprinting
application.Atthispoint,youasresourceownerarenolongerinvolvedinthe
process.

4. Theclientapplicationgetstheauthorizationcode,andmustexchangethisshort-livedcodefor
anaccesstoken.Theclientapplicationsendsanotherrequesttotheauthorizationserver,
sayingithasacodethatprovestheuserhasauthorizedittoaccesstheirphotos,andnowissue
theaccesstokentobesentontotheAPI(resourceserver).Theauthorizationserververifiesthe
authorizationcodeandreturnsanaccesstoken.
5. TheclientapplicationsendstheaccesstokentotheAPI(resourceserver),andreceivesthe
photosasrequested.

API Gateway OAuth server features


APIGatewayprovidesthefollowingfeaturestosupportOAuth2.0:

l Web-basedclientapplicationregistration
l Generationofauthorizationcodes,accesstokens,andrefreshtokens

l SupportforthefollowingOAuthauthenticationflows:
o Authorizationcodegrant(webserver)
o Implicitgrant(useragent)
o Resourceownerpasswordcredentials
o Clientcredentialsgrant
o JWT
o Refreshtoken
o Revoketoken
o Tokeninformationservice
o SAMLassertion
Formoreinformationonthesupportedflows,seeAPIGatewayOAuth2.0authenticationflows
onpage17.
l Sampleclientapplicationsforallsupportedflows
ThefollowingdiagramshowstherolesoftheAPIGatewayasanOAuth2.0resourceserverand
authorizationserver:

Oracle API Gateway11.1.2.4.0 OAuth User Guide15


2 Introduction to API Gateway OAuth 2.0 server

Further information
FormoredetailsontheAPIGatewayOAuth2.0support,seethefollowingtopics:

l APIGatewayOAuth2.0authenticationflowsonpage17
l SetupAPIGatewayasanOAuth2.0serveronpage43
l APIGatewayasanOAuth2.0authorizationserveronpage48
l APIGatewayasanOAuth2.0resourceserveronpage75
FormoredetailsontheOAuth2.0specification,goto:

OAuth2.0AuthorizationFramework

Oracle API Gateway11.1.2.4.0 OAuth User Guide16


API Gateway OAuth 2.0
authentication flows 3
APIGatewaycanusetheOAuth2.0protocolforauthenticationandauthorization.APIGatewaycan
actasanOAuth2.0authorizationserverandsupportsseveralOAuth2.0flowsthatcovercommon
webserver,JavaScript,device,installedapplication,andserver-to-serverscenarios.Thissection
describeseachofthesupportedOAuth2.0flowsindetail,andshowshowtorunsamplescripts
demonstratingtheflows.

TheAPIGatewaysupportsthefollowingauthenticationflows:

l Authorizationcodegrant(webserver)Thewebserverauthenticationflowisusedby
applicationsthatarehostedonasecureserver.Acriticalaspectofthewebserverflowisthatthe
servermustbeabletoprotecttheissuedclientapplication'ssecret.
l Implicitgrant(useragent)Theuseragentauthenticationflowisusedbyclientapplications
residingintheuser'sdevice.Thiscouldbeimplementedinabrowserusingascriptinglanguage
suchasJavaScriptorFlash.Theseclientapplicationscannotkeeptheclientapplicationsecret
confidential.
l ResourceownerpasswordcredentialsThisusernameandpasswordauthenticationflowcanbe
usedwhentheclientapplicationalreadyhastheresourceowner'scredentials.
l ClientcredentialsgrantThisusernameandpasswordflowisusedwhentheclientapplication
needstodirectlyaccessitsownresourcesontheresourceserver.Onlytheclientapplication's
credentialsareusedinthisflow.Theresourceowner'scredentialsarenotrequired.
l JWTThisflowissimilartoOAuth2.0clientcredentials.AJSONWebToken(JWT)isaJSON-
basedsecuritytokenencodingthatenablesidentityandsecurityinformationtobesharedacross
securitydomains.

l RefreshtokenAftertheclientapplicationhasbeenauthorizedforaccess,itcanusearefresh
tokentogetanewaccesstoken.Thisisonlydoneaftertheconsumeralreadyhasreceivedan
accesstokenusingtheauthorizationcodegrantorresourceownerpasswordcredentialsflow.
l RevoketokenArevoketokenrequestcausestheremovaloftheclientapplicationpermissions
associatedwiththeparticulartokentoaccesstheend-user'sprotectedresources.
l TokeninformationserviceTheOAuthtokeninformationservicerespondstorequestsfor
informationonaspecifiedOAuth2.0accesstoken.
l SAMLassertionTheOAuth2.0Access Token using SAML AssertionfilterenablesanOAuth
clienttorequestanaccesstokenusingaSAMLassertion.Thisflowisusedwhenaclientwishes
toutilizeanexistingtrustrelationship,expressedthroughthesemanticsoftheSAMLassertion,
withoutadirectuserapprovalstepattheauthorizationserver.

Oracle API Gateway11.1.2.4.0 OAuth User Guide17


3 API Gateway OAuth 2.0 authentication flows

Run the sample scripts


APIGatewayincludessampleJythonscriptsforallsupportedOAuthflowsinthefollowingdirectory
ofyourAPIGatewayinstallation:

INSTALL_DIR/samples/scripts/oauth

Torunasamplescript:

1. OpenaUNIXshellorDOScommandpromptinthefollowingdirectory:

INSTALL_DIR/samples/scripts

2. Usetherun.shorrun.batutilitytoexecutetheappropriatescript.
Thefollowingexamplesshowhowtoruntheimplicit_grant.pysamplescript:

Windows

run.bat oauth\implicit_grant.py

UNIX/Linux

sh run.sh oauth/implicit_grant.py

Authorization code grant (or web server)


flow
Theauthorizationcodeorwebserverflowissuitableforclientsthatcaninteractwiththeend-user's
user-agent(typicallyawebbrowser),andthatcanreceiveincomingrequestsfromtheauthorization
server(canactasanHTTPserver).Theauthorizationcodeflowisalsoknownasthethree-legged
OAuthflow.

Theauthorizationcodeflowisasfollows:

1. ThewebserverredirectstheusertotheAPIGatewayactingasanauthorizationserverto
authenticateandauthorizetheservertoaccessdataontheirbehalf.
2. Aftertheuserapprovesaccess,thewebserverreceivesacallbackwithanauthorizationcode.
3. Afterobtainingtheauthorizationcode,thewebserverpassesbacktheauthorizationcodeto
obtainanaccesstokenresponse.
4. Aftervalidatingtheauthorizationcode,theAPIGatewaypassesbackatokenresponsetothe
webserver.
5. Afterthetokenisgranted,thewebserveraccessestheuser'sdata.

Oracle API Gateway11.1.2.4.0 OAuth User Guide18


3 API Gateway OAuth 2.0 authentication flows

Obtain an access token


Thissectiondetailsthestepsforobtaininganaccesstoken.

Web server redirects user to authorization endpoint


Redirecttheusertotheauthorizationendpointwiththefollowingparameters:

Parameter Description

response_ Required.Mustbesettocode.
type

client_id Required.TheclientIDgeneratedwhentheapplicationwasregisteredinthe
ClientApplicationRegistry.

redirect_ Optional.Thelocationwheretheauthorizationcodewillbesent.Thisvaluemust
uri matchoneofthevaluesprovidedintheClientApplicationRegistry.

scope Optional.Aspacedelimitedlistofscopes,whichindicatetheaccesstothe
resourceowner'sdatabeingrequestedbytheapplication.

state Optional.Anystatetheconsumerwantsreflectedbacktoitafterapprovalduring
thecallback.

Oracle API Gateway11.1.2.4.0 OAuth User Guide19


3 API Gateway OAuth 2.0 authentication flows

ThefollowingisanexampleURL:

https://apigateway/oauth/authorize?client_id=SampleConfidentialApp
&response_type=code
&&redirect_uri=http%3A%2F%2Flocalhost%3A8090%2Fauth%2Fredirect.html
&scope=https%3A%2F%2Flocalhost%3A8090%2Fauth%2Fuserinfo.email

Note Duringthissteptheresourceownerusermustapproveaccessfortheapplicationweb
servertoaccesstheirprotectedresources,asshowninthefollowingexamplewindow.

Web server receives callback with authorization code


Theresponsetotheaboverequestissenttotheredirect_uri.Iftheuserapprovestheaccess
request,theresponsecontainsanauthorizationcodeandthestateparameter(ifincludedinthe
request).Iftheuserdoesnotapprovetherequest,theresponsecontainsanerrormessage.All
responsesarereturnedtothewebserveronthequerystring.Forexample:

https://localhost/oauth_callback&code=9srN6sqmjrvG5bWvNB42PCGju0TFVV

Web server exchanges authorization code for access


token
Afterthewebserverreceivestheauthorizationcode,itcanexchangetheauthorizationcodeforan
accesstokenandarefreshtoken.ThisrequestisanHTTPSPOST,andincludesthefollowing
parameters:

Parameter Description

grant_type Required.Mustbesettoauthorization_code.

Oracle API Gateway11.1.2.4.0 OAuth User Guide20


3 API Gateway OAuth 2.0 authentication flows

Parameter Description

code Required.Theauthorizationcodereceivedintheredirectabove.

redirect_ Required.TheredirectURLregisteredfortheapplicationduringapplication
uri registration.

client_id Optional.Theclient_idobtainedduringapplicationregistration.

client_ Optional.Theclient_secretobtainedduringapplicationregistration.
secret

format Optional.Expectedreturnformat.Thedefaultisjson.Possiblevaluesare:
l urlencoded
l json
l xml

Note Iftheclient_idandclient_secretarenotprovidedasparametersintheHTTPPOST,
theymustbeprovidedintheHTTPbasicauthenticationheader:Authorization
base64Encoded(client_id:client_secret)

ThefollowingexampleHTTPSPOSTshowssomeparameters:

POST /api/oauth/token HTTP/1.1


Content-Type:application/x-www-form-urlencoded

client_id=SampleConfidentialApp&client_secret=6808d4b6-ef09-4b0d-8f28-3b05da9c48ec
&code=9srN6sqmjrvG5bWvNB42PCGju0TFVV
&redirect_uri=http%3A%2F%2Flocalhost%3A8090%2Fauth%2Fredirect.html
&grant_type=authorization_code
&format=query

Web server receives access token


Aftertherequestisverified,theAPIGatewaysendsaresponsetotheclient.Thefollowing
parametersareintheresponsebody:

Parameter Description

access_ Thetokenthatcanbesenttotheresourceservertoaccesstheprotected
token resourcesoftheresourceowner(user).

refresh_ Atokenthatcanbeusedtoobtainanewaccesstoken.
token

expires Theremaininglifetimeontheaccesstoken.

Oracle API Gateway11.1.2.4.0 OAuth User Guide21


3 API Gateway OAuth 2.0 authentication flows

Parameter Description

type Indicatesthetypeoftokenreturned.ThisfieldalwayshasavalueofBearer.

Thefollowingisanexampleresponse:

HTTP/1.1 200 OK
Cache-Control:no-store
Content-Type:application/json
Pragma:no-cache{
"access_token":O91G451HZ0V83opz6udiSEjchPynd2Ss9......",
"token_type":"Bearer",
"expires_in":"3600",
}

Web server uses access token to access protected


resources
Afterthewebserverhasobtainedanaccesstoken,itcangainaccesstoprotectedresourcesonthe
resourceserverbyplacingitinanAuthorization:BearerHTTPheader:

GET /oauth/protected HTTP/1.1


Authorization:Bearer O91G451HZ0V83opz6udiSEjchPynd2Ss9
Host:apigateway.com

Forexample,thecurlcommandtocallaprotectedresourcewithanaccesstokenisasfollows:

curl -H "Authorization:Bearer O91G451HZ0V83opz6udiSEjchPynd2Ss9"


https://apigateway.com/oauth/protected

Run the sample client


ThefollowingJythonsampleclientcreatesandsendsanauthorizationrequestfortheauthorization
grantflowtotheauthorizationserver:

INSTALL_DIR/samples/scripts/oauth/authorization_code.py

Torunthesample,performthefollowingsteps:

1. OpenashellpromptattheINSTALL_DIR/samples/scriptsdirectory.
2. Executethefollowingcommand:

> run oauth/authorization_code.py

Thescriptoutputsthefollowing:

Oracle API Gateway11.1.2.4.0 OAuth User Guide22


3 API Gateway OAuth 2.0 authentication flows

> Go to the URL here:


http://127.0.0.1:8080/api/oauth/authorize?client_id=SampleConfidentialApp
&response_type=code
&scope=https%3A%2F%2Flocalhost%3A8090%2Fauth%2Fuserinfo.email
&redirect_uri=https%3A%2F%2Flocalhost%2Foauth_callback
Enter Authorization code in dialog

3. CopytheURLintoabrowser,andperformthefollowingstepsasprompted:
l Providelogincredentialstotheauthorizationserver.ThedefaultClientApplicationRegistry
usernameisregadmin.
l Whenprompted,grantaccesstotheclientapplicationtoaccesstheprotectedresource.
Aftertheresourceownerhasauthorizedandapprovedaccesstotheapplication,the
authorizationserverredirectsafragmentcontainingtheauthorizationcodetotheredirection
URI.Forexample:

https://localhost/oauth_callback&code=AaI5Or3RYB2uOgiyqVsLs1ATIY0ll0

Inthisexample,theauthorizationcodeis:

AaI5Or3RYB2uOgiyqVsLs1ATIY0ll0

4. EnterthisvalueintotheEnter Authorization Codedialog.

Thescriptexchangestheauthorizationcodeforanaccesstoken,andthenaccessesthe
protectedresourceusingtheaccesstoken.Forexample:

Enter Authorization code in dialog


AuthZ code:AaI5Or3RYB2uOgiyqVsLs1ATIY0ll0
Exchange authZ code for access token
Sending up access token request using grant_type set to authorization_code
Response from access token request:200
Parsing the json response
**********************ACCESS TOKEN
RESPONSE***********************************
Access token received from authorization server
icPgKP2uVUD2thvAZ5ENhsQb66ffnZEC
XHyRQEz5zP8aGzcobLV3AR
Access token type received from authorization server Bearer
Access token expiry time:3599

Oracle API Gateway11.1.2.4.0 OAuth User Guide23


3 API Gateway OAuth 2.0 authentication flows

Refresh token:NpNbzIVVvj8MhMmcWx2zsawxxJ3YADfc0XIxlZvw0tIhh8

****************************************************************************
**
Now we can try access the protected resource using the access token
Executing get request on the protected url
Response from protected resource request is:200
<html>Congrats! You've hit an OAuth protected resource</html>

Further information
FordetailsonAPIGatewayfiltersthatsupportthisflow,seethefollowingtopics:
l Getaccesstokenusingauthorizationcodeonpage53
l Consumeauthorizationrequestsonpage64

Implicit grant (or user agent) flow


Theimplicitgrant(useragent)authenticationflowisusedbyclientapplications(consumers)
residingintheuser'sdevice.Thiscouldbeimplementedinabrowserusingascriptinglanguage
suchasJavaScript,orfromamobiledevice,oradesktopapplication.Theseconsumerscannotkeep
theclientsecretconfidential(applicationpasswordorprivatekey).

Theuseragentflowisasfollows:

1. ThewebserverredirectstheusertotheAPIGatewayactingasanauthorizationserverto
authenticateandauthorizetheservertoaccessdataontheirbehalf.
2. Aftertheuserapprovesaccess,thewebserverreceivesacallbackwithanaccesstokeninthe
fragmentoftheredirectURL.
3. Afterthetokenisgranted,theapplicationcanaccesstheprotecteddatawiththeaccesstoken.

Oracle API Gateway11.1.2.4.0 OAuth User Guide24


3 API Gateway OAuth 2.0 authentication flows

Obtain an access token


Thissectiondetailsthestepsforobtaininganaccesstoken.

Web server redirects user to authorization endpoint


Redirecttheusertotheauthorizationendpointwiththefollowingparameters:

Parameter Description

response_ Required.Mustbesettotoken.
type

client_id Required.TheclientIDgeneratedwhentheapplicationwasregisteredinthe
ClientApplicationRegistry.

redirect_ Optional.Thelocationwheretheaccesstokenwillbesent.Thisvaluemustmatch
uri oneofthevaluesprovidedintheClientApplicationRegistry.

scope Optional.Aspacedelimitedlistofscopes,whichindicatestheaccesstothe
resourceowner'sdatarequestedbytheapplication.

state Optional.Anystatetheconsumerwantsreflectedbacktoitafterapprovalduring
thecallback.

ThefollowingisanexampleURL:

https://apigateway/oauth/authorize?client_id=SampleConfidentialApp

Oracle API Gateway11.1.2.4.0 OAuth User Guide25


3 API Gateway OAuth 2.0 authentication flows

&response_type=token
&&redirect_uri=http%3A%2F%2Flocalhost%3A8090%2Fauth%2Fredirect.html
&scope=https%3A%2F%2Flocalhost%3A8090%2Fauth%2Fuserinfo.email

Note Duringthissteptheresourceownerusermustapproveaccessfortheapplication(web
server)toaccesstheirprotectedresources,asshowninthefollowingexamplewindow.

Web server receives callback with access token


Theresponsetotheaboverequestissenttotheredirect_uri.Iftheuserapprovestheaccess
request,theresponsecontainsanaccesstokenandthestateparameter(ifincludedintherequest).
Forexample:

https://localhost/oauth_callback#access_token=19437jhj2781FQd44AzqT3Zg
&token_type=Bearer
&expires_in=3600

Iftheuserdoesnotapprovetherequest,theresponsecontainsanerrormessage.

Aftertherequestisverified,theAPIGatewaysendsaresponsetotheclient.Thefollowing
parametersarecontainedinthefragmentoftheredirect:

Parameter Description

access_ Thetokenthatcanbesenttotheresourceservertoaccesstheprotected
token resourcesoftheresourceowner(user).

expires Theremaininglifetimeontheaccesstoken.

type Indicatesthetypeoftokenreturned.ThisfieldalwayshasavalueofBearer.

Oracle API Gateway11.1.2.4.0 OAuth User Guide26


3 API Gateway OAuth 2.0 authentication flows

Parameter Description

state Optional.Iftheclientapplicationsentavalueforstateintheoriginal
authorizationrequest,thestateparameterispopulatedwiththisvalue.

Web server uses access token to access protected


resources
Aftertheapplicationhasobtainedanaccesstoken,itcangainaccesstoprotectedresourcesonthe
resourceserverbyplacingitinanAuthorization:BearerHTTPheader:

GET /oauth/protected HTTP/1.1


Authorization:Bearer O91G451HZ0V83opz6udiSEjchPynd2Ss9
Host:apigateway.com

Forexample,thecurlcommandtocallaprotectedresourcewithanaccesstokenisasfollows:

curl -H "Authorization:Bearer O91G451HZ0V83opz6udiSEjchPynd2Ss9"


https://apigateway.com/oauth/protected

Run the sample client


ThefollowingJythonsampleclientcreatesandsendsanauthorizationrequestfortheimplicitgrant
flowtotheauthorizationserver:

INSTALL_DIR/samples/scripts/oauth/implicit_grant.py

Torunthesample,performthefollowingsteps:

1. OpenashellpromptattheINSTALL_DIR/samples/scriptsdirectory.
2. Executethefollowingcommand:

> run oauth/implicit_grant.py

Thescriptoutputsthefollowing:

> Go to the URL here:


http://127.0.0.1:8080/api/oauth/authorize?client_id=SampleConfidentialApp
&response_type=token
&scope=https%3A%2F%2Flocalhost%3A8090%2Fauth%2Fuserinfo.email
&redirect_uri=https%3A%2F%2Flocalhost%2Foauth_callback
&state=1956901292
Enter Access Token code in dialog

Aftertheresourceownerhasauthorizedandapprovedaccesstotheapplication,the
authorizationserverredirectstotheredirectionURIafragmentcontainingtheaccesstoken.For

Oracle API Gateway11.1.2.4.0 OAuth User Guide27


3 API Gateway OAuth 2.0 authentication flows

example:

https://localhost/oauth_callback#
access_token=4owzGyokzLLQB5FH4tOMk7Eqf1wqYfENEDXZ1mGvN7u7a2Xexy2OU9
&expires_in=3599
&state=1956901292
&token_type=Bearer

Inthisexample,theaccesstokenis:

4owzGyokzLLQB5FH4tOMk7Eqf1wqYfENEDXZ1mGvN7u7a2Xexy2OU9

3. EnterthisvalueintotheEnter Access Token from fragmentdialog.

Thescriptattemptstoaccesstheprotectedresourceusingtheaccesstoken.Forexample:

**********************ACCESS TOKEN RESPONSE******************************


Access token received from authorization server
4owzGyokzLLQB5FH4tOMk7Eqf1wqYfEN
EDXZ1mGvN7u7a2Xexy2OU9

****************************************************************************
**
Now we can try access the protected resource using the access token
Executing get request on the protected url
Response from protected resource request is:200
<html>Congrats! You've hit an OAuth protected resource</html>

Further information
FordetailsontheAPIGatewayfilterthatsupportsthisflow,seeConsumeauthorizationrequestson
page64.

Oracle API Gateway11.1.2.4.0 OAuth User Guide28


3 API Gateway OAuth 2.0 authentication flows

Resource owner password credentials


flow
Theresourceownerpasswordcredentialsflowisalsoknownastheusername-password
authenticationflow.Thisflowcanbeusedasareplacementforanexistingloginwhenthe
consumeralreadyhastheuser'scredentials.

Theresourceownerpasswordcredentialsgranttypeissuitableincaseswheretheresourceowner
hasatrustrelationshipwiththeclient(forexample,thedeviceoperatingsystemorahighly
privilegedapplication).Theauthorizationservershouldtakespecialcarewhenenablingthisgrant
type,andonlyallowitwhenotherflowsarenotviable.

Thisgranttypeissuitableforclientscapableofobtainingtheresourceowner'scredentials(user
nameandpassword,typicallyusinganinteractiveform).Itisalsousedtomigrateexistingclients
usingdirectauthenticationschemessuchasHTTPbasicordigestauthenticationtoOAuthby
convertingthestoredcredentialstoanaccesstoken.

Request an access token


TheclienttokenrequestshouldbesentinanHTTPPOSTtothetokenendpointwiththefollowing
parameters:

Parameter Description

grant_type Required.Mustbesettopassword.

username Required.Theresourceowner'susername.

password Required.Theresourceowner'spassword.

scope Optional.Thescopeoftheauthorization.

Oracle API Gateway11.1.2.4.0 OAuth User Guide29


3 API Gateway OAuth 2.0 authentication flows

Parameter Description

format Optional.Expectedreturnformat.Thedefaultisjson.Possiblevaluesare:
l urlencoded
l json
l xml

ThefollowingisanexampleHTTPPOSTrequest:

POST /api/oauth/token HTTP/1.1


Content-Length:424
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:192.168.0.48:8080
Authorization:Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
grant_type=password&username=johndoe&password=A3ddj3w

Handle the response


TheAPIGatewayvalidatestheresourceowner'scredentialsandauthenticatestheclientagainstthe
ClientApplicationRegistry.Anaccesstoken,andoptionalrefreshtoken,issentbacktotheclienton
success.Forexample,avalidresponseisasfollows:

HTTP/1.1 200 OK
Cache-Control:no-store
Content-Type:application/json
Pragma:no-cache
{
"access_token":O91G451HZ0V83opz6udiSEjchPynd2Ss9......",
"token_type":"Bearer",
"expires_in":"3600",
"refresh_token":"8722gffy2229220002iuueee7GP..........."
}

Run the sample client


ThefollowingJythonsampleclientsendsarequesttotheauthorizationserverusingtheresource
ownerpasswordcredentialsflow:

INSTALL_DIR/samples/scripts/oauth/resourceowner_password_credentials.py

Torunthesample,openashellpromptatINSTALL_DIR/samples/scripts,andexecutethe
followingcommand:

> run oauth/resourceowner_password_credentials.py

Thescriptoutputsthefollowing:

Oracle API Gateway11.1.2.4.0 OAuth User Guide30


3 API Gateway OAuth 2.0 authentication flows

Sending up access token request using grant_type set to password


Response from access token request:200
Parsing the json response
**********************ACCESS TOKEN RESPONSE***********************************
Access token received from authorization server lrGHhFhFwSmycXStIza1jjvXlSaac9
JNIgviF7oPiV8OnxlSIsrxVA
Access token type received from authorization server Bearer
Access token expiry time:3600
******************************************************************************
Now we can try access the protected resource using the access token
Executing get request on the protected url
Response from protected resource request is:200
<html>Congrats! You've hit an OAuth protected resource</html>

Further information
FordetailsontheAPIGatewayfilterthatsupportsthisflow,seeGetaccesstokenusingresource
ownercredentialsonpage70.

Client credentials grant flow


Theclientcredentialsgranttypemustonlybeusedbyconfidentialclients.Theclientcanrequestan
accesstokenusingonlyitsclientcredentials(orothersupportedmeansofauthentication)whenthe
clientisrequestingaccesstotheprotectedresourcesunderitscontrol.Theclientcanalsorequest
accesstothoseofanotherresourceownerthathasbeenpreviouslyarrangedwiththeauthorization
server(themethodofwhichisbeyondthescopeofthespecification).

Oracle API Gateway11.1.2.4.0 OAuth User Guide31


3 API Gateway OAuth 2.0 authentication flows

Request an access token


TheclienttokenrequestshouldbesentinanHTTPPOSTtothetokenendpointwiththefollowing
parameters:

Parameter Description

grant_type Required.Mustbesettoclient_credentials.

scope Optional.Thescopeoftheauthorization.

format Optional.Expectedreturnformat.Thedefaultisjson.Possiblevaluesare:
l urlencoded
l json
l xml

ThefollowingisanexamplePOSTrequest:

POST /api/oauth/token HTTP/1.1


Content-Length:424
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:192.168.0.48:8080
Authorization:Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
grant_type=client_credentials

Handle the response


TheAPIGatewayauthenticatestheclientagainsttheClientApplicationRegistry.Anaccesstokenis
sentbacktotheclientonsuccess.Arefreshtokenisnotincludedinthisflow.Anexamplevalid
responseisasfollows:

HTTP/1.1 200 OK
Cache-Control:no-store
Content-Type:application/json
Pragma:no-cache
{
"access_token":O91G451HZ0V83opz6udiSEjchPynd2Ss9......",
"token_type":"Bearer",
"expires_in":"3600"
}

Oracle API Gateway11.1.2.4.0 OAuth User Guide32


3 API Gateway OAuth 2.0 authentication flows

Run the sample client


ThefollowingJythonsampleclientsendsarequesttotheauthorizationserverusingtheclient
credentialsflow:

INSTALL_DIR/samples/scripts/oauth/client_credentials.py

Torunthesample,openashellpromptatINSTALL_DIR/samples/scripts,andexecutethe
followingcommand:

> run oauth/client_credentials.py

Thescriptoutputsthefollowing:

Sending up access token request using grant_type set to client_credentials


Response from access token request:200
Parsing the json response
**********************ACCESS TOKEN RESPONSE***********************************
Access token received from authorization server OjtVvNusLg2ujy3a6IXHhavqdE
PtK7qSmIj9fLl8qywPyX8bKEsjqF
Access token type received from authorization server Bearer
Access token expiry time:3599
******************************************************************************
Now we can try access the protected resource using the access token
Response from protected resource request is:200
<html>Congrats! You've hit an OAuth protected resource</html>

Further information
FordetailsontheAPIGatewayfilterthatsupportsthisflow,seeGetaccesstokenusingclient
credentialsonpage55.

JWT flow
AJSONWebToken(JWT)isaJSON-basedsecuritytokenencodingthatenablesidentityand
securityinformationtobesharedacrosssecuritydomains.

Oracle API Gateway11.1.2.4.0 OAuth User Guide33


3 API Gateway OAuth 2.0 authentication flows

IntheOAuth2.0JWTflow,theclientapplicationisassumedtobeaconfidentialclientthatcan
storetheclientapplication'sprivatekey.TheX.509certificatethatmatchestheclient'sprivatekey
mustberegisteredintheClientApplicationRegistry.TheAPIGatewayusesthiscertificatetoverify
thesignatureoftheJWTclaim.

FormoredetailsontheOAuth2.0JWTflow,goto:
http://self-issued.info/docs/draft-ietf-oauth-jwt-bearer-00.html

Create a JWT bearer token


TocreateaJWTbearertoken,performthefollowingsteps:

1. ConstructaJWTheaderinthefollowingformat:

{"alg":"RS256"}

2. Base64urlencodetheJWTheader,whichresultsinthefollowing:

eyJhbGciOiJSUzI1NiJ9

3. CreateaJWTclaimsset,whichconformstothefollowingrules:
l Theissuer(iss)mustbetheOAuthclient_idortheremoteaccessapplicationfor
whichthedeveloperregisteredtheircertificate.
l Theaudience(aud)mustmatchthevalueconfiguredintheJWTfilter.Bydefault,this
valueisasfollows:

http://apigateway/api/oauth/token

l Thevalidity(exp)mustbetheexpirationtimeoftheassertion,withinfiveminutes,
expressedasthenumberofsecondsfrom1970-01-01T0:0:0ZmeasuredinUTC.
l Thetimetheassertionwasissued(iat)measuredinsecondsafter00:00:00UTC,January
1,1970.
l TheJWTmustbesigned(usingRSASHA256).
l TheJWTmustconformwiththegeneralformatrulesspecifiedhere:
http://tools.ietf.org/html/draft-jones-json-web-token
Forexample:

Oracle API Gateway11.1.2.4.0 OAuth User Guide34


3 API Gateway OAuth 2.0 authentication flows

{
"iss":"SampleConfidentialApp",
"aud":"http://apigateway/api/oauth/token",
"exp":"1340452126",
"iat":"1340451826"
}

4. Base64urlencodetheJWTclaimsset,resultingin:

eyJpc3MiOiJTYW1wbGVDb25maWRlbnRpYWxBcHAiLCJhdWQiOiJodHRwOi8vYXBpc2VydmV

yL2FwaS9vYXV0aC90b2tlbiIsImV4cCI6IjEzNDA0NTIxMjYiLCJpYXQiOiIxMzQwNDUxODI2In0
=

5. CreateanewstringfromtheencodedJWTheaderfromstep2,andtheencodedJWTclaimsset
fromstep4,andappendthemasfollows:

Base64URLEncode(JWT Header) + . + Base64URLEncode(JWT Claims Set)

Thisresultsinastringasfollows:

eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiAiU2FtcGxlQ29uZmlkZW50aWFsQXBwIiwgImF1ZCI6ICJ
odHRw

Oi8vYXBpc2VydmVyL2FwaS9vYXV0aC90b2tlbiIsICJleHAiOiAiMTM0MTM1NDYwNSIsICJpYXQi
OiAi
MTM0MTM1NDMwNSJ9

6. Signtheresultingstringinstep5usingSHA256withRSA.Thesignaturemustthenbe
Base64urlencoded.Thesignatureisthenconcatenatedwitha.charactertotheendofthe
Base64urlrepresentationoftheinputstring.TheresultisthefollowingJWT(linebreaksadded
forclarity):

{Base64url encoded header}.


{Base64url encoded claim set}.

Thisresultsinastringasfollows:

eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiAiU2FtcGxlQ29uZmlkZW50aWFsQXBwIiwgImF1ZCI6ICJ
odHR

wOi8vYXBpc2VydmVyL2FwaS9vYXV0aC90b2tlbiIsICJleHAiOiAiMTM0MTM1NDYwNSIsICJpYXQ
iOiA

iMTM0MTM1NDMwNSJ9.ilWR8O8OlbQtT5zBaGIQjveOZFIWGTkdVC6LofJ8dN0akvvD0m7IvUZtPp
4dx3
KdEDj4YcsyCEAPhfopUlZO3LE-iNPlbxB5dsmizbFIc2oGZr7Zo4IlDf92OJHq9DGqwQosJ-
s9GcIRQk
-IUPF4lVy1Q7PidPWKR9ohm3c2gt8

Oracle API Gateway11.1.2.4.0 OAuth User Guide35


3 API Gateway OAuth 2.0 authentication flows

Request an access token


TheJWTbearertokenshouldbesentinanHTTPPOSTtothetokenendpointwiththefollowing
parameters:

Parameter Description

grant_type Required.Mustbesetto
urn:ietf:params:oauth:grant-type:jwt-bearer.

assertion Required.MustbesettotheJWTbearertoken,base64url-encoded.

format Optional.Expectedreturnformat.Thedefaultisjson.Possiblevaluesare:
l urlencoded
l json
l xml

ThefollowingisanexamplePOSTrequest:

POST /api/oauth/token HTTP/1.1


Content-Length:424
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:192.168.0.48:8080
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
&assertion=eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiAiU2FtcGxlQ29uZmlkZW50a
WFsQXBwIiwgImF1ZCI6ICJodHRwOi8vYXBpc2VydmVyL2FwaS9vYXV0aC90b2tlbiIsI
CJleHAiOiAiMTM0MTM1NDYwNSIsICJpYXQiOiAiMTM0MTM1NDMwNSJ9.ilWR8O8OlbQt
T5zBaGIQjveOZFIWGTkdVC6LofJ8dN0akvvD0m7IvUZtPp4dx3KdEDj4YcsyCEAPhfop
UlZO3LE-iNPlbxB5dsmizbFIc2oGZr7Zo4IlDf92OJHq9DGqwQosJ-s9GcIRQk-IUPF
4lVy1Q7PidPWKR9ohm3c2gt8

Handle the response


TheAPIGatewayreturnsanaccesstokeniftheJWTclaimandaccesstokenrequestareproperly
formed,andtheJWThasbeensignedbytheprivatekeymatchingtheregisteredcertificateforthe
clientapplicationintheClientApplicationRegistry.

Forexample,avalidresponseisasfollows:

HTTP/1.1 200 OK
Cache-Control:no-store
Content-Type:application/json
Pragma:no-cache
{
"access_token":O91G451HZ0V83opz6udiSEjchPynd2Ss9......",
"token_type":"Bearer",

Oracle API Gateway11.1.2.4.0 OAuth User Guide36


3 API Gateway OAuth 2.0 authentication flows

"expires_in":"3600",
}

Run the sample client


ThefollowingJythonsamplecreatesandsendsaJWTbearertokentotheauthorizationserver:

INSTALL_DIR/samples/scripts/oauth/jwt.py

Torunthesample,openashellpromptatINSTALL_DIR/samples/scripts,andexecutethe
followingcommand:

> run oauth/jwt.py

Further information
FordetailsontheAPIGatewayfilterthatsupportsthisflow,seeGetaccesstokenusingJWTonpage
58.

Revoke token
Insomecasesausermightwishtorevokeaccessgiventoanapplication.Anaccesstokencanbe
revokedbycallingtheAPIGatewayrevokeserviceandprovidingtheaccesstokentoberevoked.A
revoketokenrequestcausestheremovaloftheclientpermissionsassociatedwiththeparticular
tokentoaccesstheend-user'sprotectedresources.

Theendpointforrevoketokenrequestsisasfollows:

https://HOST:8089/api/oauth/revoke

Oracle API Gateway11.1.2.4.0 OAuth User Guide37


3 API Gateway OAuth 2.0 authentication flows

ThetokentoberevokedshouldbesenttotherevoketokenendpointinanHTTPPOSTwiththe
followingparameters:

Parameter Description

token Required.Atokentoberevoked(forexample,
4eclEUX1N6oVIOoZBbaDTI977SV3T9KqJ3ayOvs4gqhGA4).

token_ Optional.Ahintspecifyingthetokentype.Forexample,access_tokenor
type_hint refresh_token.

ThefollowingisanexamplePOSTrequest:

POST /api/oauth/revoke HTTP/1.1


Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:192.168.0.48:8080
Authorization:Basic U2FtcGxlQ29uZmlkZW50aWFsQXBwOjY4MDhkNGI2LWVmMDktNGIwZC04ZjI4LT
NiMDVkYTljNDhlYw==token=4eclEUX1N6oVIOoZBbaDTI977SV3T9KqJ3ayOvs4gqhGA4
&token_type_hint=refresh_token

Run the sample client


ThefollowingJythonsampleclientcreatesatokenrevokerequesttotheauthorizationserver:

INSTALL_DIR/samples/scripts/oauth/revoke_token.py

Torunthesample,openashellpromptatINSTALL_DIR/samples/scripts,andexecutethe
followingcommand:

> run oauth/revoke_token.py

Pastethevalueassociatedwiththetokeninthedialog:

Selectthetypeoftokenhintinthenextdialog:

Oracle API Gateway11.1.2.4.0 OAuth User Guide38


3 API Gateway OAuth 2.0 authentication flows

Ifyouselectnone,notoken_type_hintparameterisspecifiedinthePOSTrequest.Ifyouselect
access_token,thePOSTrequestcontainstoken_type_hint=access_token.Ifyouselect
refresh_token,thePOSTrequestcontainstoken_type_hint=refresh_token.

Whentheauthorizationserverreceivesthetokenrevocationrequest,itfirstvalidatestheclient
credentialsandverifieswhethertheclientisauthorizedtorevoketheparticulartokenbasedonthe
clientidentity.

Note Onlytheclientthatwasissuedthetokencanrevokeit.

Theauthorizationserverdecideswhetherthetokenisanaccesstokenorarefreshtoken:

l Ifitisanaccesstoken,thistokenisrevoked.
l Ifitisarefreshtoken,allaccesstokensissuedfortherefreshtokenareinvalidated,andthe
refreshtokenisrevoked.

Response codes
ThefollowingHTTPstatusresponsecodesarereturned:
l HTTP200ifthetokenwasrevokedsuccessfullyorifaninvalidtokenwassubmitted.
l HTTP401ifclientauthenticationfailed.
l HTTP403iftheclientisnotauthorizedtorevokethetoken.
Thefollowingisanexampleresponse:

Token to be revoked:3eXnUZzkODNGb9D94Qk5XhiV4W4gu9muZ56VAYoZiot4WNhIZ72D3
Revoking token...............
Response from revoke token request is:200
Successfully revoked token

Further information
FordetailsontheAPIGatewayfilterthatsupportsthisflow,seeRevoketokenonpage73.

Token information service


YoucanusethetokeninformationservicetovalidatethatanaccesstokenwasissuedbytheAPI
Gateway.ArequesttothetokenInfoserviceisanHTTPGETrequestforinformationinaspecified
OAuth2.0accesstoken.

Oracle API Gateway11.1.2.4.0 OAuth User Guide39


3 API Gateway OAuth 2.0 authentication flows

Theendpointforthetokeninformationserviceisasfollows:

https://HOST:8089/api/oauth/tokeninfo

GettinginformationaboutatokenfromtheauthorizationserveronlyrequiresaGETrequesttothe
tokeninfoendpoint.Forexample:

GET /api/oauth/tokeninfo HTTP/1.1


Host:192.168.0.48:8080
access_token=4eclEUX1N6oVIOoZBbaDTI977SV3T9KqJ3ayOvs4gqhGA4

Thisrequestincludesthefollowingparameter:

Parameter Description

access_ Required.Atokenthatyouwantinformationabout(forexample:
token 4eclEUX1N6oVIOoZBbaDTI977SV3T9KqJ3ayOvs4gqhGA4)

Thefollowingexampleusesthisparameter:

https://apigateway/api/oauth/tokeninfo?access_token=4eclEUX1
N6oVIOoZBbaDTI977SV3T9KqJ3ayOvs4gqhGA4

Run the sample client


ThefollowingJythonsampleclientcreatesatokenrevokerequesttotheauthorizationserver:

INSTALL_DIR/samples/scripts/oauth/token_info.py

Oracle API Gateway11.1.2.4.0 OAuth User Guide40


3 API Gateway OAuth 2.0 authentication flows

Torunthesample,openashellpromptatINSTALL_DIR/samples/scripts,andexecutethe
followingcommand:

> run oauth/token_info.py

Thisdisplaysthefollowingdialog:

Whentheauthorizationserverreceivesthetokeninformationrequest,itfirstensuresthetokenisin
itscache(EhCacheorDatabase),andensuresthetokenisvalidandhasnotexpired.

Thefollowingisanexampleresponse:

Get token info for this token:BcYGjPOQSCrtbEc1F0ag8zf6OT9rCaMLiI1dYjFLT5zhxz3x5ScrdN


Response from token info request is:200
**********************TOKEN INFO RESPONSE***********************************
Token audience received from authorization server:SampleConfidentialApp
Scopes user consented to:https://localhost:8090/auth/userinfo.email
Token expiry time:3566
User id :admin
******************************************************************************

Response codes
ThefollowingHTTPstatuscodesarereturned:
l 200ifprocessingissuccessful
l 400onfailure
TheresponseissentbackasaJSONmessage.Forexample:

{
"audience" :"SampleConfidentialApp",
"user_id" :"admin",
"scope" :"https://localhost:8090/auth/userinfo.email",
"expires_in" :2518
}

Youcangetadditionalinformationabouttheaccesstokenusingmessageattributes.Formore
details,seeOAuth2.0messageattributesonpage113.

Oracle API Gateway11.1.2.4.0 OAuth User Guide41


3 API Gateway OAuth 2.0 authentication flows

Further information
FordetailsontheAPIGatewayfilterthatsupportsthisflow,seeGetaccesstokeninformationon
page52.

Oracle API Gateway11.1.2.4.0 OAuth User Guide42


Set up API Gateway as an
OAuth 2.0 server 4
ThissectiondescribeshowtosetupAPIGatewayasanOAuthauthorizationserverandOAuth
resourceserver.Itdescribesthefollowing:

l HowtoenabletheOAuth2.0endpointsusedtomanageclientapplicationsSeeEnableOAuth
managementonpage43.
l HowtoimportthepreregisteredsampleclientapplicationsprovidedwithAPIGatewaySee
Importsampleclientapplicationsonpage45.
l HowtomigrateexistingOAuth2.0clientapplicationsSeeMigrateexistingclientapplications
onpage46.

Enable OAuth management


TheOAuthserviceisnotavailableinthebasicinstallation.Youmustdeployitmanually.A
conveniencescriptisprovidedin$VDISTDIR/samples/scripts/oauthfordeployingtheOAuth
2.0serviceslistener,supportingpolicies,andsampleapplications.VDISTDIRisthedirectoryin
whichAPIGatewayisinstalled.

TodeploytheOAuthservice,changedirectoryto$VDISTDIR/samples/scripts,andrunthe
deployOAuthConfig.pyscriptasfollows:

UNIX/Linux

./run.sh oauth/deployOAuthConfig.py

Windows

run.bat oauth\deployOAuthConfig.py

ThisdeploystheOAuthservercomponentsonport8089andtheclientdemoonport8088.

Theparametersforthescriptareasfollows:

Option Description

-h, Displayhelpforthescript.
--help

-uUSERNAME, Theadministratorusernametousetoconnecttothetopology.Thisis
-- theadministratorusernameyouenteredduringAPIGateway
username=USERNAME installation.

Oracle API Gateway11.1.2.4.0 OAuth User Guide43


4 Set up API Gateway as an OAuth 2.0 server

Option Description

-pPASSWORD, Thepasswordfortheadministratorusertoconnecttothetopology.
-- ThisistheadministratorpasswordyouenteredduringAPIGateway
password=PASSWORD installation.

--port=PORT TheporttheClientApplicationRegistryislisteningon.Thedefaultis
8089.

--admin=ADMIN TheadministratorusernamefortheClientApplicationRegistry.The
defaultisregadmin.

--adminpw=ADMINPW TheadministratorpasswordfortheClientApplicationRegistry.

--type=TYPE Thedeploymenttype.Theoptionsare:
l authzserver
l clientdemo
l all
Thedefaultisall.

-gGROUP, Thegroupname.
--group=GROUP

-nSERVICE, Theservicename.
--service=SERVICE

TheAPIGatewayprovidesthefollowingendpointsusedtomanageOAuth2.0clientapplications:

Description URL

AuthorizationEndpoint(RESTAPI) https://HOST:8089/api/oauth/authorize

TokenEndpoint(RESTAPI) https://HOST:8089/api/oauth/token

TokenInfoEndpoint(RESTAPI) https://HOST:8089/api/oauth/tokeninfo

RevokeEndpoint(RESTAPI) https://HOST:8089/api/oauth/revoke

ClientApplicationRegistry(HTML https://HOST:8089
Interface)

ClientApplicationRegistry(RESTAPI) https://HOST:8089/api/kps/ClientApplicationRegistry

Inthistable,HOSTreferstothemachineonwhichAPIGatewayisinstalled.

Note Toenabletheseendpoints,youmustfirstenabletheOAuthlistenerportintheAPI
Gateway.Formoredetails,seeEnableOAuthendpointsonpage45.

Oracle API Gateway11.1.2.4.0 OAuth User Guide44


4 Set up API Gateway as an OAuth 2.0 server

Enable OAuth endpoints


ToenabletheOAuthmanagementendpointsonyourAPIGateway,performthefollowingsteps:

1. InthePolicyStudiotree,selectListeners > API Gateway > OAuth 2.0 Services >


Ports.
2. Right-clicktheOAuth 2.0 Interfaceinthepanelontheright,andselectEdit.
3. SelectEnable Interfaceinthedialog.
4. ClicktheDeploybuttoninthetoolbar.
5. EnteradescriptionandclickFinish.
Note OnLinux-basedsystems,suchasOracleEnterpriseLinux,youmustopenthefirewallto
allowexternalaccesstoport8089.Ifyouneedtochangetheportnumber,setthevalueof
theenv.PORT.OAUTH2.SERVICESenvironmentvariable.Fordetailsonsettingexternal
environmentvariablesforAPIGatewayinstances,seetheAPIGatewayDeploymentand
PromotionGuide.

Import sample client applications


TheAPIGatewayshipswithanumberofpreregisteredsampleclientapplications.Forexample,the
defaultsampleclientapplicationsincludethefollowing:

Client ID Client secret

SampleConfidentialApp 6808d4b6-ef09-4b0d-8f28-3b05da9c48ec

SamplePublicApp 3b001542-e348-443b-9ca2-2f38bd3f3e84

Note Thesampleclientapplicationsarefordemonstrationpurposesonlyandshouldberemoved
beforemovingtheauthorizationserverintoproduction.

IfyouhaveusedthedeployOAuthConfig.pyscripttodeploytheOAuthservice,thesesamples
arealreadyimported.FormoreinformationonusingthedeployOAuthConfig.pyscript,see
EnableOAuthmanagementonpage43.

IfyoudidnotusethedeployOAuthConfig.pyscript,thesamplesarenotimported,andyoumust
importthemmanuallyintotheClientApplicationRegistry.Performthefollowingsteps:

1. AccesstheClientApplicationRegistrywebinterfaceatthefollowingURL:

https://localhost:8089

2. EntertheClientApplicationRegistryusernameandpassword.Thedefaultusernameis
regadmin.
3. ClicktheImportbuttonatthetoprightofthewindow.
4. Selectthefollowingsamplefileinthedialog:

$VDISTDIR/samples/scripts/oauth/sampleapps.dat

Oracle API Gateway11.1.2.4.0 OAuth User Guide45


4 Set up API Gateway as an OAuth 2.0 server

VDISTDIRspecifiesthedirectoryinwhichAPIGatewayisinstalled.
5. YoucanalsoenteraDecryption Secretinthedialog.However,thesampleapps.datfileis
inplaintextformat,anddoesnotrequireapassword.
6. ClickOKtoimportthesampleapplications.Thefollowingfigureshowstheseapplications
importedintotheClientApplicationRegistry:

Alternatively,youcanusethefollowingscripttoimportthesampleclientapplicationdatawithout
usingtheClientApplicationRegistrywebinterface:

$VDISTDIR/samples/scripts/oauth/importSampleData.py

Editthisscripttoconfigureyourusercredentialsandfilelocation.

Migrate existing client applications


IfyouaremigratingfromAPIGatewayversion11.1.2.0.x,usethefollowingscripttomigrateyour
existingOAuthclientapplications:

$VDISTDIR/samples/scripts/oauth/migrateFrom71.py

Thisscriptenablesyoutofirstexportyourexistingclientapplicationdata,whichyoucanthen
importasdescribedinImportsampleclientapplicationsonpage45.Thisscripthasa--password
parameterthatyoucanusetoencrypttheexporteddatafortransport.

Tomigrateyourexistingclientapplications,performthefollowingsteps:

1. AfterinstallingAPIGateway11.1.2.4.0,copythe
$VDISTIR/samples/oauth/migrateFrom71.pyfiletothesamelocationinyourexisting
APIGateway11.1.2.0.xinstallation:

$VDISTIR/samples/oauth/migrateFrom71.py

2. InyourexistingAPIGateway11.1.2.0.xinstallation,ensurethat
$VDISTIR/samples/scripts/common.pyhasthecorrectdefServerNameand
defGroupNamevariablessetforyourexistingtopology.
3. RunthemigrateFrom71.pyscriptagainstyourrunningversion11.1.2.0.xAdminNode
ManagerandAPIGateway.Thescriptoutputsthefollowingfile:

$VDISTIR/samples/oauth/appregistry/encodedapps.dat

Note Toencryptthedata,runthescriptwiththe--passwordparameter.

Oracle API Gateway11.1.2.4.0 OAuth User Guide46


4 Set up API Gateway as an OAuth 2.0 server

4. Checktheencodedapps.datfiletoensurethattheexporthasbeensuccessful.
5. Importtheencodedapps.datintoarunningAPIGateway11.1.2.4.0usingtheClient
ApplicationRegistrywebinterface.Formoredetails,seeImportsampleclientapplicationson
page45.
Note Whenimportingencrypteddata,youmustenterthepasswordintheDecryption
Secretfield.

Oracle API Gateway11.1.2.4.0 OAuth User Guide47


API Gateway as an OAuth
2.0 authorization server 5
ThissectiondescribeshowtoconfigureAPIGatewayasanOAuthauthorizationserver.Itdescribes
thefollowing:

l HowtomanageOAuthaccesstokensandauthorizationcodesSeeManageaccesstokensand
authorizationcodesonpage48.

Relatedtopics

l OAuth2.0authorizationserverfiltersonpage51
l OAuth2.0messageattributesonpage113

Manage access tokens and authorization


codes
APIGatewaycanstoregeneratedauthorizationcodesandaccesstokensinitscaches,inan
embeddeddatabase,orinarelationaldatabase.Theauthorizationserverissuestokenstoclientson
behalfofaresourceowner.ThesetokensareusedwhenauthenticatingsubsequentAPIcallstothe
resourceserver.Theseissuedtokensmustbepersistedsothatsubsequentclientrequeststothe
authorizationservercanbevalidated.

YoucanconfigureauthorizationcodeandaccesstokenstoresundertheLibraries > OAuth2


StoresnodeinthePolicyStudiotree.Theauthorizationservercancacheauthorizationcodesand
accesstokensdependingontheOAuthflow.Thestepsforaddinganauthorizationcodecacheare
similartoaddinganaccesstokencache.

Theauthorizationserveroffersthefollowingpersistentstorageoptionsforaccesstokensand
authorizationcodes:

l APIGatewaycache(default)
l RelationalDatabaseManagementSystem(RDBMS)
l EmbeddedApacheCassandradatabase
ThefollowingfigureshowstheseoptionsinPolicyStudio:

Oracle API Gateway11.1.2.4.0 OAuth User Guide48


5 API Gateway as an OAuth 2.0 authorization server

ThePurge expired tokens everysettingenablesyoutoconfigureatimeintervalinseconds


afterwhichabackgroundprocesspollsthedatabaselookingforexpiredaccessorrefreshtokensor
authorizationcodesandpurgesthem.

Store in a cache
Tostoreaccesstokensorauthorizationcodesinacache,performthefollowingsteps:

1. Right-clickAccess Token StoresinthePolicyStudiotree,andselectAdd Access Token


Store.
2. Inthedialog,selectStore in a cache,andselectthebrowsebuttontodisplaythecache
configurationdialog.
3. Addanewcache(forexample,OAuth Access Token Cache).
FormoredetailsonAPIGatewaycaches,seetheAPIGatewayPolicyDeveloperGuide.

Store in a relational database


Tostoreaccesstokensorauthorizationcodesinarelationaldatabase,performthefollowingsteps:

1. Createthesupportingschemarequiredforthestorageofaccesstokens,refreshtokens,and
authorizationcodesusingtheSQLcommandsin$VDISTIR\system\conf\sql\DBMS_
TYPE\oauth-server.sqlwhereDBMS_TYPEisthedatabasemanagementsystembeing
used.SchemaareprovidedforMicrosoftSQLServer,MySQL,Oracle,andIBMDB2.
2. Right-clickAccess Token StoresinthePolicyStudiotree,andselectAdd Access Token
Store.
3. Inthedialog,selectStore in a database,andselectthebrowsebuttontodisplayadatabase
configurationdialog.

Oracle API Gateway11.1.2.4.0 OAuth User Guide49


5 API Gateway as an OAuth 2.0 authorization server

4. Completethedatabaseconfigurationdetails.ThefollowingexampleusesaMySQLinstance
namedoauth_db.Formoredetails,seetheAPIGatewayPolicyDeveloperGuide.

Store in Cassandra
TostoreaccesstokensorauthorizationcodesinApacheCassandra,performthefollowingsteps:

1. Right-clickAccess Token StoresinthePolicyStudiotree,andselectAdd Access Token


Store.
2. Thisdisplaysadialog.SelectStore in Cassandra.
3. YoucanconfigureReadandWriteconsistencylevelsfortheCassandradatabase.These
controlhowup-to-dateandsynchronizedarowofdataisonallofitsreplicas.Thedefault
ReadsettingofONEmeansthatthedatabasereturnsaresponsefromtheclosestreplica.The
defaultWritesettingofANYmeansthatawritemustbewrittentoatleastonereplicanode.
FormoredetailsonApacheCassandra,seetheAPIGatewayKeyPropertyStoreUserGuide.

Oracle API Gateway11.1.2.4.0 OAuth User Guide50


OAuth 2.0 authorization
server filters 6
ThissectiondescribesthefiltersyoucanusewhenAPIGatewayisactingasanOAuthauthorization
server.Theseinclude:

Filter Related flows

Consumeauthorizationrequestsonpage64 l Authorizationcodegrant(orweb
server)flowonpage18
l Implicitgrant(oruseragent)flowon
page24

Getaccesstokenusingauthorizationcodeon Authorizationcodegrant(orwebserver)
page53 flowonpage18

Getaccesstokenusingresourceowner Resourceownerpasswordcredentialsflow
credentialsonpage70 onpage29

Getaccesstokenusingclientcredentialson Clientcredentialsgrantflowonpage31
page55

GetaccesstokenusingJWTonpage58 JWTflowonpage33

GetaccesstokenusingSAMLassertiononpage SAMLassertion
61

Getaccesstokeninformationonpage52 Tokeninformationserviceonpage39

Revoketokenonpage73 Revoketokenonpage37

Refreshaccesstokenonpage68 Refreshtoken

Relatedtopics

l OAuth2.0messageattributesonpage113

Oracle API Gateway11.1.2.4.0 OAuth User Guide51


6 OAuth 2.0 authorization server filters

Get access token information

Overview
TheOAuth2.0Access Token InformationfilterisusedtoreturnaJSONdescriptionofthe
specifiedOAuth2.0accesstoken.OAuthaccesstokensareusedtograntaccesstospecificresources
inanHTTPserviceforaspecificperiodoftime(forexample,photosonaphotosharingwebsite).
Thisenablesuserstograntthird-partyapplicationsaccesstotheirresourceswithoutsharingallof
theirdataandaccesspermissions.

AnOAuthaccesstokencanbesenttotheresourceservertoaccesstheprotectedresourcesofthe
resourceowner(user).Thistokenisastringthatdenotesaspecificscope,lifetime,andotheraccess
attributes.FordetailsonsupportedOAuthflows,seeAPIGatewayOAuth2.0authenticationflows
onpage17.

Token settings
ConfigurethefollowingfieldsontheAccess Token Info Settingstab:
Token to verify can be found here:
Clickthebrowsebuttontoselectthelocationoftheaccesstokentoverify(forexample,inthe
defaultOAuth Access Token Store).Toaddastore,right-clickAccess Token Stores,andselect
Add Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,orinan
embeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorizationcodes
onpage48.

Where to get access token from:


Selectoneofthefollowing:

l In Query String:
Thisisthedefaultsetting.Defaultstotheaccess_tokenparameter.
l In a selector:
Defaultstothe${http.client.getCgiArgument('access_token')}selector.Formore
detailsonAPIGatewayselectors,seetheAPIGatewayPolicyDeveloperGuide.

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Oracle API Gateway11.1.2.4.0 OAuth User Guide52


6 OAuth 2.0 authorization server filters

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

Advanced settings
ThesettingsontheAdvancedtabincludethefollowing:

Return additional Access Token parameters:


ClickAddtoreturnadditionalaccesstokenparameters,andentertheNameandValueinthe
dialog.Forexample,youcouldenterDepartmentinName,andthefollowingselectorinValue:

${accesstoken.getAdditionalInformation().get("Department")

Get access token using authorization code

Overview
TheOAuth2.0Access Token using Authorization Codefilterisusedtogetanewaccesstoken
usingtheauthorizationcode.ThissupportstheOAuth2.0authorizationcodegrantorwebserver
authenticationflow,whichisusedbyapplicationsthatarehostedonasecureserver.Acritical
aspectofthisflowisthattheservermustbeabletoprotecttheissuedclientapplication'ssecret.For
moredetailsonsupportedOAuthflows,seeAPIGatewayOAuth2.0authenticationflowsonpage
17.

OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTPserviceforaspecific
periodoftime(forexample,photosonaphotosharingwebsite).Thisenablesuserstograntthird-
partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataandaccesspermissions.
AnOAuthaccesstokencanbesenttotheresourceservertoaccesstheprotectedresourcesofthe
resourceowner(user).Thistokenisastringthatdenotesaspecificscope,lifetime,andotheraccess
attributes.

Oracle API Gateway11.1.2.4.0 OAuth User Guide53


6 OAuth 2.0 authorization server filters

Application validation settings


Configurethefollowingfieldsonthistab:

Use this store to validate the Authorization Code:


Clickthebrowsebuttontoselectthestoreinwhichtovalidatetheauthorizationcode(forexample,
inthedefaultAuthz Code Store).Toaddastore,right-clickAuthorization Code Stores,and
selectAdd Authorization Code Store.Youcanstorecodesinacache,inarelationaldatabase,or
inanembeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorization
codesonpage48.

Find client application information from message:


Selectoneofthefollowing:
l In Authorization Header:
Thisisthedefaultsetting.
l In Query String:
TheClient Iddefaultstoclient_id,andClient Secretdefaultstoclient_secret.

Access token settings


Configurethefollowingfieldsonthethistab:

Access Token will be stored here:


Clickthebrowsebuttontoselectwheretostoretheaccesstoken(forexample,inthedefaultOAuth
Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,andselect
Add Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,orinan
embeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorizationcodes
onpage48.

Access Token Expiry (in secs):


Enterthenumberofsecondsbeforetheaccesstokenexpires.Defaultsto3600(onehour).

Access Token Length:


Enterthenumberofcharactersintheaccesstoken.Defaultsto54.

Access Token Type:


Entertheaccesstokentype.Thisprovidestheclientwithinformationrequiredtousetheaccess
tokentomakeaprotectedresourcerequest.Theclientcannotuseanaccesstokenifitdoesnot
understandthetokentype.DefaultstoBearer.

Refresh Token Details:


Selectoneofthefollowingoptions:
l Generate a new refresh token:
Selectthisoptiontogenerateanewaccesstokenandrefreshtokenpair.Theoldrefreshtoken
passedintherequestisremoved.Thisoptionisselectedbydefault.

Oracle API Gateway11.1.2.4.0 OAuth User Guide54


6 OAuth 2.0 authorization server filters

EnterthenumberofsecondsbeforetherefreshtokenexpiresintheRefresh Token Expiry (in


secs)field,andenterthenumberofcharactersintherefreshtokenintheRefresh Token
Lengthfield.Theexpirydefaultsto43200(12hours),andthelengthdefaultsto46.
l Do not generate a refresh token:
Selectthisoptiontogenerateanewaccesstokenonly.Theoldrefreshtokenpassedinthe
requestisremoved.
Store additional meta data with the access token which can subsequently be
retrieved:
ClickAddtostoreadditionalaccesstokenparameters,andentertheNameandValueinthedialog
(forexample,DepartmentandEngineering).

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

Get access token using client credentials

Overview
TheOAuth2.0Access Token using Client CredentialsfilterenablesanOAuthclienttorequest
anaccesstokenusingonlyitsclientcredentials.ThissupportstheOAuth2.0clientcredentialsflow,
whichisusedwhentheclientapplicationneedstodirectlyaccessitsownresourcesontheresource

Oracle API Gateway11.1.2.4.0 OAuth User Guide55


6 OAuth 2.0 authorization server filters

server.Onlytheclientapplication'scredentialsorpublic/privatekeypairareusedinthethisflow.
Theresourceowner'scredentialsarenotrequired.FormoredetailsonsupportedOAuthflows,see
APIGatewayOAuth2.0authenticationflowsonpage17.

OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTPserviceforaspecific
periodoftime(forexample,photosonaphotosharingwebsite).Thisenablesuserstograntthird-
partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataandaccesspermissions.
AnOAuthaccesstokencanbesenttotheresourceservertoaccesstheprotectedresourcesofthe
resourceowner(user).Thistokenisastringthatdenotesaspecificscope,lifetime,andotheraccess
attributes.

Application validation settings


Configurethefollowingfieldsonthistab:

Find client application information from message:


Selectoneofthefollowing:
l In Authorization Header:
Thisisthedefaultsetting.
l In Query String:
TheClient Iddefaultstoclient_id,andClient Secretdefaultstoclient_secret.

Access token settings


Configurethefollowingfieldsonthethistab:

Access Token will be stored here:


Clickthebrowsebuttontoselectwheretostoretheaccesstoken(forexample,inthedefaultOAuth
Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,andselect
Add Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,orinan
embeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorizationcodes
onpage48.

Access Token Expiry (in secs):


Enterthenumberofsecondsbeforetheaccesstokenexpires.Defaultsto3600(onehour).

Access Token Length:


Enterthenumberofcharactersintheaccesstoken.Defaultsto54.

Access Token Type:


Entertheaccesstokentype.Thisprovidestheclientwithinformationrequiredtousetheaccess
tokentomakeaprotectedresourcerequest.Theclientcannotuseanaccesstokenifitdoesnot
understandthetokentype.DefaultstoBearer.

Oracle API Gateway11.1.2.4.0 OAuth User Guide56


6 OAuth 2.0 authorization server filters

Refresh Token Details:


Selectoneofthefollowingoptions:
l Generate a new refresh token:
Selectthisoptiontogenerateanewaccesstokenandrefreshtokenpair.Theoldrefreshtoken
passedintherequestisremoved.Thisoptionisselectedbydefault.
EnterthenumberofsecondsbeforetherefreshtokenexpiresintheRefresh Token Expiry (in
secs)field,andenterthenumberofcharactersintherefreshtokenintheRefresh Token
Lengthfield.Theexpirydefaultsto43200(12hours),andthelengthdefaultsto46.
l Do not generate a refresh token:
Selectthisoptiontogenerateanewaccesstokenonly.Theoldrefreshtokenpassedinthe
requestisremoved.
Store additional meta data with the access token which can subsequently be
retrieved:
ClickAddtostoreadditionalaccesstokenparameters,andentertheNameandValueinthedialog
(forexample,DepartmentandEngineering).

Generate Token Scopes:

Whenrequestingatokenfromtheauthorizationserver,youcanspecifyaparameterfortheOAuth
scopesthatyouwishtoaccess.Whenscopesaresentintherequest,youcanselectwhetherthe
accesstokenisgeneratedonlyifthescopesintherequestmatchalloranyscopesregisteredforthe
application.Alternatively,forextraflexibility,youcangetthescopesbycallingouttoapolicy.

Selectoneofthefollowingoptionstoconfigurehowaccesstokensaregeneratedbasedon
specifiedscopes:

l Get scopes from a registered application:


SelectwhetherthescopesmustmatchAnyorAllofthescopesregisteredfortheapplicationin
theClientApplicationRegistry.DefaultstoAny.Ifnoscopesaresentintherequest,thetokenis
generatedwiththescopesregisteredfortheapplication.
l Get scopes by calling policy:
Selectapreconfiguredpolicytogetthescopes,andentertheattributethatstoresthescopesin
theScopes approved for token are stored in the attributefield.Defaultsto
scopes.for.token.Theconfiguredfilterrequiresthescopesasasetofstringsonthemessage
whiteboard.

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Oracle API Gateway11.1.2.4.0 OAuth User Guide57


6 OAuth 2.0 authorization server filters

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

Get access token using JWT

Overview
TheOAuth2.0Access Token using JWTfilterenablesanOAuthclienttorequestanaccesstoken
usingonlyaJSONWebToken(JWT).ThissupportstheOAuth2.0JWTflow,whichisusedwhen
theclientapplicationneedstodirectlyaccessitsownresourcesontheresourceserver.Onlythe
clientJWTtokenisusedinthisflow,theresourceowner'scredentialsarenotrequired.Formore
detailsonsupportedOAuthflows,seeAPIGatewayOAuth2.0authenticationflowsonpage17.

AJWTisaJSON-basedsecuritytokenencodingthatenablesidentityandsecurityinformationtobe
sharedacrosssecuritydomains.JWTsrepresentasetofclaimsasaJSONobject.Formore
informationonJWT,goto:
http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTPserviceforaspecific
periodoftime(forexample,photosonaphotosharingwebsite).Thisenablesuserstograntthird-
partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataandaccesspermissions.
AnOAuthaccesstokencanbesenttotheresourceservertoaccesstheprotectedresourcesofthe
resourceowner(user).Thistokenisastringthatdenotesaspecificscope,lifetime,andotheraccess
attributes.

Application validation settings


Configurethefollowingfieldsonthistab:

Audience (aud) must contain the following URI:


EntertheJWTaud(intendedaudience).TheJWTmustcontainanaudURIthatidentifiesthe

Oracle API Gateway11.1.2.4.0 OAuth User Guide58


6 OAuth 2.0 authorization server filters

authorizationserver,orserviceproviderdomain,asanintendedaudience.Theauthorizationserver
mustalsoverifythatitisanintendedaudiencefortheJWT.Defaultsto
http://apigateway/api/oauth/token.

Clock skew in seconds for JWT Claim:


WhencreatingtheJWT,anOAuthclientcansetcertainclaimsrelatingtotime(forexample,iat,
exp,ornbf).Thisfieldallowsyoutoenteranumberofsecondstoallowforclockskewwhen
dealingwiththeseclaims.

Iftheiatclaimispresent,theOAuthtokenserviceassertsthatthecurrenttimeisgreaterthanthe
issuedattime.Iftheexpclaimispresent,theOAuthtokenserviceassertsthatthecurrenttimeis
lessthanorequaltotheexpirytime(plusskewsecondsifconfigured).Ifthenbfclaimispresent,
theOAuthtokenserviceassertsthatthecurrenttimeisgreaterthanorequaltoexpirytime(minus
skewsecondsifconfigured).

Access token settings


Configurethefollowingfieldsonthistab:

Access Token will be stored here:


Clickthebrowsebuttontoselectwheretostoretheaccesstoken(forexample,inthedefaultOAuth
Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,andselect
Add Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,orinan
embeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorizationcodes
onpage48.

Access Token Expiry (in secs):


Enterthenumberofsecondsbeforetheaccesstokenexpires.Defaultsto3600(onehour).

Access Token Length:


Enterthenumberofcharactersintheaccesstoken.Defaultsto54.

Access Token Type:


Entertheaccesstokentype.Thisprovidestheclientwithinformationrequiredtousetheaccess
tokentomakeaprotectedresourcerequest.Theclientcannotuseanaccesstokenifitdoesnot
understandthetokentype.DefaultstoBearer.

Refresh Token Details:


Selectoneofthefollowingoptions:
l Generate a new refresh token:
Selectthisoptiontogenerateanewaccesstokenandrefreshtokenpair.Theoldrefreshtoken
passedintherequestisremoved.Thisoptionisselectedbydefault.
EnterthenumberofsecondsbeforetherefreshtokenexpiresintheRefresh Token Expiry (in
secs)field,andenterthenumberofcharactersintherefreshtokenintheRefresh Token
Lengthfield.Theexpirydefaultsto43200(12hours),andthelengthdefaultsto46.
l Do not generate a refresh token:

Oracle API Gateway11.1.2.4.0 OAuth User Guide59


6 OAuth 2.0 authorization server filters

Selectthisoptiontogenerateanewaccesstokenonly.Theoldrefreshtokenpassedinthe
requestisremoved.
Store additional meta data with the access token which can subsequently be
retrieved:
ClickAddtostoreadditionalaccesstokenparameters,andentertheNameandValueinthedialog
(forexample,DepartmentandEngineering).

Generate Token Scopes:

Whenrequestingatokenfromtheauthorizationserver,youcanspecifyaparameterfortheOAuth
scopesthatyouwishtoaccess.Whenscopesaresentintherequest,youcanselectwhetherthe
accesstokenisgeneratedonlyifthescopesintherequestmatchalloranyscopesregisteredforthe
application.Alternatively,forextraflexibility,youcangetthescopesbycallingouttoapolicy.

Selectoneofthefollowingoptionstoconfigurehowaccesstokensaregeneratedbasedon
specifiedscopes:

l Get scopes from a registered application:


SelectwhetherthescopesmustmatchAnyorAllofthescopesregisteredfortheapplicationin
theClientApplicationRegistry.DefaultstoAny.Ifnoscopesaresentintherequest,thetokenis
generatedwiththescopesregisteredfortheapplication.
l Get scopes by calling policy:
Selectapreconfiguredpolicytogetthescopes,andentertheattributethatstoresthescopesin
theScopes approved for token are stored in the attributefield.Defaultsto
scopes.for.token.Theconfiguredfilterrequiresthescopesasasetofstringsonthemessage
whiteboard.

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Oracle API Gateway11.1.2.4.0 OAuth User Guide60


6 OAuth 2.0 authorization server filters

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

Get access token using SAML assertion

Overview
TheOAuth2.0Access Token using SAML AssertionfilterenablesanOAuthclienttorequestan
accesstokenusingaSAMLassertion.ThissupportstheOAuth2.0SAMLflow,whichisusedwhena
clientwishestoutilizeanexistingtrustrelationship,expressedthroughthesemanticsoftheSAML
assertion,withoutadirectuserapprovalstepattheauthorizationserver.Formoredetailson
supportedOAuthflows,seeAPIGatewayOAuth2.0authenticationflowsonpage17.

FormoreinformationonSAML,seetheIETFdraftdocument:
SAML2.0ProfileforOAuth2.0

OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTPserviceforaspecific
periodoftime(forexample,photosonaphotosharingwebsite).Thisenablesuserstograntthird-
partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataandaccesspermissions.
AnOAuthaccesstokencanbesenttotheresourceservertoaccesstheprotectedresourcesofthe
resourceowner(user).Thistokenisastringthatdenotesaspecificscope,lifetime,andotheraccess
attributes.

SAML assertion validation settings


Configurethefollowingfieldsonthistab:
Audience and Recipient within SAML Assertion must contain the following URI:
EnteraURIthatmustbecontainedintheSAMLassertion'sintendedaudienceandrecipient.The
SAMLassertionmustcontainaURIthatidentifiestheauthorizationserverasanintendedaudience,
andthatidentifiesthetokenendpointURLoftheauthorizationserverasarecipient.Defaultsto
http://apigateway/api/oauth/token.

Drift time (seconds):


Enteradrifttimeinsecondstoallowforclockskew.

Call the following policy to verify SAML Assertion signature:


ClickthebrowsebuttontoselectapolicytoverifytheSAMLassertionsignature.

ToguaranteetheintegrityofanXMLsignatureinamessage,theAccess Token using SAML


AssertionfiltershouldusetheXML Signature Verificationfilter.Formoreinformation,seethe
XML Signature VerificationfilterintheAPIGatewayPolicyDeveloperGuide.WhenAPIGateway
receivestheassertion,itconvertstheassertionintoaW3CDOMdocumentandstoresthisvalueina

Oracle API Gateway11.1.2.4.0 OAuth User Guide61


6 OAuth 2.0 authorization server filters

messageattributenamedoauth.saml.doc.ThismessageattributeisusedbytheXML Signature
Verificationfilter.AsampleSAMLbearerpolicyflowisavailableafteryouhavecompletedsetting
upOAuth(seeSetupAPIGatewayasanOAuth2.0serveronpage43).

Access token settings


Configurethefollowingfieldsonthistab:

Access Token will be stored here:


Clickthebrowsebuttontoselectwheretostoretheaccesstoken(forexample,inthedefaultOAuth
Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,andselect
Add Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,orinan
embeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorizationcodes
onpage48.

Access Token Expiry (in secs):


Enterthenumberofsecondsbeforetheaccesstokenexpires.Defaultsto3600(onehour).

Access Token Length:


Enterthenumberofcharactersintheaccesstoken.Defaultsto54.

Access Token Type:


Entertheaccesstokentype.Thisprovidestheclientwithinformationrequiredtousetheaccess
tokentomakeaprotectedresourcerequest.Theclientcannotuseanaccesstokenifitdoesnot
understandthetokentype.DefaultstoBearer.

Refresh Token Details:


Selectoneofthefollowingoptions:
l Generate a new refresh token:
Selectthisoptiontogenerateanewaccesstokenandrefreshtokenpair.Theoldrefreshtoken
passedintherequestisremoved.Thisoptionisselectedbydefault.
EnterthenumberofsecondsbeforetherefreshtokenexpiresintheRefresh Token Expiry (in
secs)field,andenterthenumberofcharactersintherefreshtokenintheRefresh Token
Lengthfield.Theexpirydefaultsto43200(12hours),andthelengthdefaultsto46.
l Do not generate a refresh token:
Selectthisoptiontogenerateanewaccesstokenonly.Theoldrefreshtokenpassedinthe
requestisremoved.
Store additional meta data with the access token which can subsequently be
retrieved:
ClickAddtostoreadditionalaccesstokenparameters,andentertheNameandValueinthedialog
(forexample,DepartmentandEngineering).

Generate Token Scopes:

Oracle API Gateway11.1.2.4.0 OAuth User Guide62


6 OAuth 2.0 authorization server filters

Whenrequestingatokenfromtheauthorizationserver,youcanspecifyaparameterfortheOAuth
scopesthatyouwishtoaccess.Whenscopesaresentintherequest,youcanselectwhetherthe
accesstokenisgeneratedonlyifthescopesintherequestmatchalloranyscopesregisteredforthe
application.Alternatively,forextraflexibility,youcangetthescopesbycallingouttoapolicy.

Selectoneofthefollowingoptionstoconfigurehowaccesstokensaregeneratedbasedon
specifiedscopes:

l Get scopes from a registered application:


SelectwhetherthescopesmustmatchAnyorAllofthescopesregisteredfortheapplicationin
theClientApplicationRegistry.DefaultstoAny.Ifnoscopesaresentintherequest,thetokenis
generatedwiththescopesregisteredfortheapplication.
l Get scopes by calling policy:
Selectapreconfiguredpolicytogetthescopes,andentertheattributethatstoresthescopesin
theScopes approved for token are stored in the attributefield.Defaultsto
scopes.for.token.Theconfiguredfilterrequiresthescopesasasetofstringsonthemessage
whiteboard.

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

Oracle API Gateway11.1.2.4.0 OAuth User Guide63


6 OAuth 2.0 authorization server filters

Consume authorization requests

Overview
TheOAuth2.0Authorization Code FlowfilterisusedtoconsumeOAuthauthorizationrequests.
ThisfiltersupportstheOAuth2.0authorizationcode(webserver)flow,whichisusedby
applicationshostedonasecureserver.Acriticalaspectofthisflowisthattheservermustbeableto
protecttheissuedclientapplication'ssecret.Thewebserverflowissuitableforclientscapableof
interactingwiththeend-user'suser-agent(typicallyawebbrowser),andcapableofreceiving
incomingrequestsfromtheauthorizationserver(actingasanHTTPserver).Theauthorizationcode
flowisalsoknownasthethree-leggedOAuthflow.

TheOAuth2.0authorizationcodeflowisasfollows:
1. ThewebserverredirectstheusertotheAPIGatewayactingasanauthorizationserverto
authenticateandauthorizetheservertoaccessdataontheirbehalf.
2. Aftertheuserapprovesaccess,thewebserverreceivesacallbackwithanauthorizationcode.
3. Afterobtainingtheauthorizationcode,thewebserverpassesbacktheauthorizationcodeto
obtainanaccesstokenresponse.
4. Aftervalidatingtheauthorizationcode,theAPIGatewaypassesbackatokenresponsetothe
webserver.
5. Afterthetokenisgranted,thewebserveraccessestheirdata.
OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTPserviceforaspecific
periodoftime(forexample,photosonaphotosharingwebsite).Thisenablesuserstograntthird-
partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataandaccesspermissions.
AnOAuthaccesstokencanbesenttotheresourceservertoaccesstheprotectedresourcesofthe
resourceowner(user).Thistokenisastringthatdenotesaspecificscope,lifetime,andotheraccess
attributes.

TheOAuth2.0Authorization Code Flowfilteralsosupportstheimplicitgrant(useragent)flow.


Thisisusedbyclientapplications(consumers)residingintheuser'sdevice(forexample,ina
browserusingJavaScript,orfromamobiledevice,ordesktopapplication).Theseconsumers
cannotkeeptheclientsecretconfidential(applicationpasswordorprivatekey).

FormoredetailsonsupportedOAuthflows,seeAPIGatewayOAuth2.0authenticationflowson
page17.

Validation settings
ThesettingsontheValidation/Templatestabenableyoutospecifyloginandauthorization
formstoauthenticatetheresourceowner.

Configurethefollowingfields:

Login Form:

Oracle API Gateway11.1.2.4.0 OAuth User Guide64


6 OAuth 2.0 authorization server filters

EnterthefullpathtotheHTMLformthattheresourceownercanusetologin.Defaultstothevalue
${environment.VDISTDIR}/samples/oauth/templates/login.html.

Authorization Form:

EnterthefullpathtotheHTMLformthattheresourceownercanusetogrant(allowordeny)client
applicationaccesstotheresources.Defaultstothevalue${environment.VDISTDIR}
/samples/oauth/templates/requestAccess.html.

Selector:

Enteraselectorforthemessageattributethatcontainstheauthentication.subject.idofthe
currentuseriftheyhavealreadybeenauthenticated.Defaultstothe
${authentication.subject.id}messageattribute.Formoredetailsonselectors,seethe
APIGatewayPolicyDeveloperGuide.

Note PreviousversionsofAPIGatewayenabledyoutocallapolicytoauthorizetheresource
owner,andstorethesubjectinamessageattribute.Thisfieldisusedtoprovidebackwards
compatibilitywithconfigurationsusingthatoption.Ifanauthenticateduserisnotfound
inthemessage,thefilterautomaticallyusestheinternalflowandreturnsthespecified
loginform.

Authorization code settings


ConfigurethefollowingfieldsontheAuthz Code Detailstab:

Authorization Code will be stored here:


Clickthebrowsebuttontoselectwheretocachetheauthorizationcode(forexample,inthedefault
Authz Code Store).Toaddanauthorizationcodestore,right-clickAuthorization Code Stores,
andselectAdd Authorization Code Store.Youcanstorecodesinacache,inarelational
database,orinanembeddedCassandradatabase.Formoredetails,seeManageaccesstokensand
authorizationcodesonpage48.

Location of Access Code redirect page:

EnterthefullpathtotheHTMLpageusedfortheaccesscodeHTTPredirect.Defaultstothe
following:

${environment.VDISTDIR}/samples/oauth/templates/showAccessCode.html

VDISTDIRspecifiesthedirectoryinwhichtheAPIGatewayisinstalled.

Length:

Enterthenumberofcharactersintheauthorizationcode.Defaultsto30.

Expiry (in secs):

Enterthenumberofsecondsbeforetheauthorizationcodeexpires.Defaultsto600(10minutes).

Additional parameters to store for this Authorization Code:

Oracle API Gateway11.1.2.4.0 OAuth User Guide65


6 OAuth 2.0 authorization server filters

Tostoreadditionalmetadatawiththeauthorizationcode,clickAdd,andentertheNameand
Valueinthedialog(forexample,DepartmentandEngineering).Whenadditionaldataisset,it
isthenavailableintheAccess Token using Authorization Codefilterwhentheauthorization
codeisexchangedforanaccesstoken.Youcanalsospecifythefieldsinthistableusingselectors.
Formoredetailsonselectors,seetheAPIGatewayPolicyDeveloperGuide.

Note Ifyouenteredparametersfortheauthorizationcodeandparametersfortheaccesstoken,
thedatawillbemerged.Forexample,ifyousetName:Johnand
Department:Engineeringasadditionalparametersfortheauthorizationcode,andset
Department:HRasanadditionalparameterfortheaccesstoken,thetokeniscreatedwith
Name:JohnandDepartment:HR.

Access token settings


ConfigurethefollowingfieldsontheAccess Token Detailstab:

Access Token will be stored here:

Clickthebrowsebuttontoselectwheretocachetheaccesstoken(forexample,inthedefault
OAuth Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,
andselectAdd Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,or
inanembeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorization
codesonpage48.

Expiry (in secs):

Enterthenumberofsecondsbeforetheaccesstokenexpires.Defaultsto3600(onehour).

Length:

Enterthenumberofcharactersintheaccesstoken.Defaultsto54.

Type:

Entertheaccesstokentype.Thisprovidestheclientwithinformationrequiredtousetheaccess
tokentomakeaprotectedresourcerequest.Theclientcannotuseanaccesstokenifitdoesnot
understandthetokentype.DefaultstoBearer.

Additional parameters to store for this Access Token:

ClickAddtostoreadditionalaccesstokenparameters,andentertheNameandValueinthedialog
(forexample,Department,Engineering).

Generate Token Scopes:

Whenrequestingatokenfromtheauthorizationserver,youcanspecifyaparameterfortheOAuth
scopesthatyouwishtoaccess.Whenscopesaresentintherequest,youcanselectwhetherthe
accesstokenisgeneratedonlyifthescopesintherequestmatchalloranyscopesregisteredforthe
application.Alternatively,forextraflexibility,youcangetthescopesbycallingouttoapolicy.

Selectoneofthefollowingoptionstoconfigurehowaccesstokensaregeneratedbasedon
specifiedscopes:

Oracle API Gateway11.1.2.4.0 OAuth User Guide66


6 OAuth 2.0 authorization server filters

l Get scopes from a registered application:


SelectwhetherthescopesmustmatchAnyorAllofthescopesregisteredfortheapplicationin
theClientApplicationRegistry.DefaultstoAny.Ifnoscopesaresentintherequest,thetokenis
generatedwiththescopesregisteredfortheapplication.
l Get scopes by calling policy:
Selectapreconfiguredpolicytogetthescopes,andentertheattributethatstoresthescopesin
theScopes approved for token are stored in the attributefield.Defaultsto
scopes.for.token.Theconfiguredfilterrequiresthescopesasasetofstringsonthemessage
whiteboard.

Advanced settings
ThesettingsontheAdvancedtabincludemonitoringsettingsandcookiesettings.

Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

ThetrafficmonitoringoptionsenableyoutoviewmessagetrafficinAPIGatewayManager.Formore
informationontrafficmonitoring,seetheAPIGatewayAdministratorGuide.

Record Outbound Transactions

Selectwhethertorecordoutboundmessagetraffic.YoucanusethissettingtooverridetheRecord
Outbound TransactionssettinginServer Settings > Monitoring > Traffic Monitor.This
settingisselectedbydefault.

Resource Owner Cookie

Enterthenameoftheresourceowner'scookieintheCookie Namefield.

Authorization Session Cookie

Oracle API Gateway11.1.2.4.0 OAuth User Guide67


6 OAuth 2.0 authorization server filters

Enterthefollowingdetailsforthesessioncookie:

l CookieNameNameofthesessioncookie
l DomainDomainvaluefortheSet-Cookieheader
l PathPathvaluefortheSet-Cookieheader
l ExpiresinThelengthoftimeuntilthecookieexpires
l SecureSelectthecheckboxtoaddasecureflagtotheSet-Cookieheader
l HttpOnlySelectthecheckboxtoaddaHttpOnlyflagtotheSet-Cookieheader

Refresh access token

Overview
TheOAuth2.0Refresh Access TokenfilterenablesanOAuthclienttogetanewaccesstoken
usingarefreshtoken.ThisfiltersupportstheOAuth2.0refreshtokenflow.Aftertheclient
consumerhasbeenauthorizedforaccess,theycanusearefreshtokentogetanewaccesstoken
(sessionID).Thisisonlydoneaftertheconsumeralreadyhasreceivedanaccesstokenusingeither
thewebserveroruser-agentflow.FormoredetailsonsupportedOAuthflows,seeAPIGateway
OAuth2.0authenticationflowsonpage17.

Application validation settings


Configurethefollowingfieldsonthistab:

Find client application information from message:


Selectoneofthefollowing:
l In Authorization Header:
Thisisthedefaultsetting.
l In Query String:
TheClient Iddefaultstoclient_id,andClient Secretdefaultstoclient_secret.

Access token settings


Configurethefollowingfieldsonthistab:

Access Token will be stored here:


Clickthebrowsebuttontoselectwheretostoretheaccesstoken(forexample,inthedefaultOAuth
Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,andselect

Oracle API Gateway11.1.2.4.0 OAuth User Guide68


6 OAuth 2.0 authorization server filters

Add Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,orinan


embeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorizationcodes
onpage48.

Access Token Expiry (in secs):


Enterthenumberofsecondsbeforetheaccesstokenexpires.Defaultsto3600(onehour).

Access Token Length:


Enterthenumberofcharactersintheaccesstoken.Defaultsto54.

Access Token Type:


Entertheaccesstokentype.Thisprovidestheclientwithinformationrequiredtousetheaccess
tokentomakeaprotectedresourcerequest.Theclientcannotuseanaccesstokenifitdoesnot
understandthetokentype.DefaultstoBearer.

Refresh Token Details:


Selectoneofthefollowingoptions:
l Generate a new refresh token:
Selectthisoptiontogenerateanewaccesstokenandrefreshtokenpair.Theoldrefreshtoken
passedintherequestisremoved.Thisoptionisselectedbydefault.
EnterthenumberofsecondsbeforetherefreshtokenexpiresintheRefresh Token Expiry (in
secs)field,andenterthenumberofcharactersintherefreshtokenintheRefresh Token
Lengthfield.Theexpirydefaultsto43200(12hours),andthelengthdefaultsto46.
l Do not generate a refresh token:

Selectthisoptiontogenerateanewaccesstokenonly.Theoldrefreshtokenpassedinthe
requestisremoved.
l Preserve the existing refresh token:
Selectthisoptiontogenerateanewaccesstokenandpreservetheexistingrefreshtoken.The
refreshtokenpassedintherequestissentbackwiththeaccesstokenresponse.
Store additional meta data with the access token which can subsequently be
retrieved:
ClickAddtostoreadditionalaccesstokenparameters,andentertheNameandValueinthedialog
(forexample,DepartmentandEngineering).

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Oracle API Gateway11.1.2.4.0 OAuth User Guide69


6 OAuth 2.0 authorization server filters

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

Get access token using resource owner


credentials

Overview
TheOAuth2.0Resource Owner Credentialsfilterisusedtodirectlyobtainanaccesstokenand
anoptionalrefreshtoken.ThissupportstheOAuth2.0resourceownerpasswordcredentialsflow,
whichcanbeusedasareplacementforanexistingloginwhentheconsumerclientalreadyhasthe
user'scredentials.FormoredetailsonsupportedOAuthflows,seeAPIGatewayOAuth2.0
authenticationflowsonpage17.

OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTPserviceforaspecific
periodoftime(forexample,photosonaphotosharingwebsite).Thisenablesuserstograntthird-
partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataandaccesspermissions.
AnOAuthaccesstokencanbesenttotheresourceservertoaccesstheprotectedresourcesofthe
resourceowner(user).Thistokenisastringthatdenotesaspecificscope,lifetime,andotheraccess
attributes.

Application validation settings


Configurethefollowingfieldsonthistab:

Authenticate Resource Owner


Selectoneofthefollowing:

l Authenticate credentials using this repository:


Selectoneofthefollowingfromthelist:

Oracle API Gateway11.1.2.4.0 OAuth User Guide70


6 OAuth 2.0 authorization server filters

o SimpleActiveDirectoryRepository
o LocalUserStore
l Call this policy:
Clickthebrowsebuttontoselectapolicytoauthenticatetheresourceowner.Youcanusethe
Policy will store subject in selectortextboxtospecifywherethepolicyisstored.Defaults
tothe${authentication.subject.id}messageattribute.Formoredetailsonselectors,see
theAPIGatewayPolicyDeveloperGuide.
Find client application information from message:
Selectoneofthefollowing:
l In Authorization Header:
Thisisthedefaultsetting.
l In Query String:
TheClient Iddefaultstoclient_id,andClient Secretdefaultstoclient_secret.

Access token settings


Configurethefollowingfieldsonthethistab:

Access Token will be stored here:


Clickthebrowsebuttontoselectwheretostoretheaccesstoken(forexample,inthedefaultOAuth
Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,andselect
Add Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,orinan
embeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorizationcodes
onpage48.

Access Token Expiry (in secs):


Enterthenumberofsecondsbeforetheaccesstokenexpires.Defaultsto3600(onehour).

Access Token Length:


Enterthenumberofcharactersintheaccesstoken.Defaultsto54.

Access Token Type:


Entertheaccesstokentype.Thisprovidestheclientwithinformationrequiredtousetheaccess
tokentomakeaprotectedresourcerequest.Theclientcannotuseanaccesstokenifitdoesnot
understandthetokentype.DefaultstoBearer.

Refresh Token Details:


Selectoneofthefollowingoptions:
l Generate a new refresh token:
Selectthisoptiontogenerateanewaccesstokenandrefreshtokenpair.Theoldrefreshtoken
passedintherequestisremoved.Thisoptionisselectedbydefault.
EnterthenumberofsecondsbeforetherefreshtokenexpiresintheRefresh Token Expiry (in
secs)field,andenterthenumberofcharactersintherefreshtokenintheRefresh Token
Lengthfield.Theexpirydefaultsto43200(12hours),andthelengthdefaultsto46.

Oracle API Gateway11.1.2.4.0 OAuth User Guide71


6 OAuth 2.0 authorization server filters

l Do not generate a refresh token:


Selectthisoptiontogenerateanewaccesstokenonly.Theoldrefreshtokenpassedinthe
requestisremoved.
l Preserve the existing refresh token:
Selectthisoptiontogenerateanewaccesstokenandpreservetheexistingrefreshtoken.The
refreshtokenpassedintherequestissentbackwiththeaccesstokenresponse.
Store additional meta data with the access token which can subsequently be
retrieved:
ClickAddtostoreadditionalaccesstokenparameters,andentertheNameandValueinthedialog
(forexample,DepartmentandEngineering).

Generate Token Scopes:

Whenrequestingatokenfromtheauthorizationserver,youcanspecifyaparameterfortheOAuth
scopesthatyouwishtoaccess.Whenscopesaresentintherequest,youcanselectwhetherthe
accesstokenisgeneratedonlyifthescopesintherequestmatchalloranyscopesregisteredforthe
application.Alternatively,forextraflexibility,youcangetthescopesbycallingouttoapolicy.

Selectoneofthefollowingoptionstoconfigurehowaccesstokensaregeneratedbasedon
specifiedscopes:

l Get scopes from a registered application:


SelectwhetherthescopesmustmatchAnyorAllofthescopesregisteredfortheapplicationin
theClientApplicationRegistry.DefaultstoAny.Ifnoscopesaresentintherequest,thetokenis
generatedwiththescopesregisteredfortheapplication.

l Get scopes by calling policy:


Selectapreconfiguredpolicytogetthescopes,andentertheattributethatstoresthescopesin
theScopes approved for token are stored in the attributefield.Defaultsto
scopes.for.token.Theconfiguredfilterrequiresthescopesasasetofstringsonthemessage
whiteboard.

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Oracle API Gateway11.1.2.4.0 OAuth User Guide72


6 OAuth 2.0 authorization server filters

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

ThetrafficmonitoringoptionsenableyoutoviewmessagetrafficinAPIGatewayManager.Formore
informationontrafficmonitoring,seetheAPIGatewayAdministratorGuide.

Record Outbound Transactions

Selectwhethertorecordoutboundmessagetraffic.YoucanusethissettingtooverridetheRecord
Outbound TransactionssettinginServer Settings > Monitoring > Traffic Monitor.This
settingisselectedbydefault.

Revoke token

Overview
TheOAuth2.0Revoke a TokenfilterisusedtorevokeaspecifiedOAuth2.0accessorrefresh
token.Arevoketokenrequestcausestheremovaloftheclientpermissionsassociatedwiththe
specifiedtokenusedtoaccesstheuser'sprotectedresources.FormoredetailsonsupportedOAuth
flows,seeAPIGatewayOAuth2.0authenticationflowsonpage17.

OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTPserviceforaspecific
periodoftime(forexample,photosonaphotosharingwebsite).Thisenablesuserstograntthird-
partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataandaccesspermissions.
OAuthrefreshtokensaretokensissuedbytheauthorizationservertotheclientthatcanbeusedto
obtainanewaccesstoken.

Revoke token settings


Configurethefollowingfieldsonthistab:
Token to be revoked can be found here:
Clickthebrowsebuttontoselectthecachetorevokethetokenfrom(forexample,inthedefault
OAuth Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token Stores,
andselectAdd Access Token Store.Youcanstoretokensinacache,inarelationaldatabase,or
inanembeddedCassandradatabase.Formoredetails,seeManageaccesstokensandauthorization
codesonpage48.

Oracle API Gateway11.1.2.4.0 OAuth User Guide73


6 OAuth 2.0 authorization server filters

Find client application information from message:


Selectoneofthefollowing:
l In Authorization Header:
Thisisthedefaultsetting.
l In Query String:
TheClient Iddefaultstoclient_id,andClient Secretdefaultstoclient_secret.

Monitoring settings
Thereal-timemonitoringoptionsenableyoutoviewserviceusageinAPIGatewayManager.For
moreinformationonreal-timemonitoring,seetheAPIGatewayAdministratorGuide.

Enable monitoring
Selectthisoptiontoenablereal-timemonitoring.Ifthisisenabledyoucanviewserviceusageinthe
web-basedAPIGatewayManagertool.

Which attribute is used to identify the client


Enterthemessageattributetousetoidentifyauthenticatedclients.Thedefaultis
authentication.subject.id,whichstorestheidentifieroftheauthenticateduser(forexample,
theusernameoruser'sX.509DistinguishedName).

Composite Context
Thissettingenablesyoutoselectaservicecontextasacompositecontextinwhichmultipleservice
contextsaremonitoredduringtheprocessingofamessage.Thissettingisnotselectedbydefault.

Forexample,theAPIGatewayreceivesamessage,andsendsittoserviceAfirst,andthento
serviceB.Monitoringisperformedseparatelyforeachservicebydefault.However,youcanseta
compositeservicecontextbeforeserviceAandserviceBthatincludesbothservices.This
compositeservicepassesifbothservicescompletesuccessfully,andmonitoringisalsoperformed
onthecompositeservicecontext.

Oracle API Gateway11.1.2.4.0 OAuth User Guide74


API Gateway as an OAuth
2.0 resource server 7
ThissectiondescribeshowtoconfigureAPIGatewayasanOAuthresourceserver.Itdescribesthe
following:

l HowtousetheClientApplicationRegistrywebinterfacetoregisterandmanageclient
applicationsSeeRegisterandmanageOAuthclientapplicationsonpage75.
l HowtomanagetheOAuthscopesthataclientapplicationcanaccessSeeManageOAuth
scopesonpage76.

Relatedtopics

l OAuth2.0resourceserverfiltersonpage80
l OAuth2.0messageattributesonpage113

Register and manage OAuth client


applications
ClientapplicationsthatsendOAuthrequeststotheAPIGatewaysauthorizationservermustbe
registeredwiththeauthorizationserver.Thissectiondescribeshowtoregisterandmanageclient
applications(andthescopestheycanaccess)usingtheClientApplicationRegistryweb-based
interface.

Note YoumustperformthestepsdescribedinSetupAPIGatewayasanOAuth2.0serveron
page43(forexample,enabletheOAuthendpointsandimportormigrateclient
applications)beforeyoucanmanageclientapplicationsusingtheClientApplication
Registry.

Manage client applications


APIGatewayprovidestheClientApplicationRegistryweb-basedinterfaceformanagingclient
applications.APIGatewayalsoprovidestheClientApplicationRegistryRESTAPItoenableyouto
manageclientapplicationsonthecommandline.

YoucanaccesstheClientApplicationRegistrywebinterfaceatthefollowingURL:

https://localhost:8089

LoginusingtheClientApplicationRegistryusernameandpassword.Thedefaultusernameis
regadmin.

Oracle API Gateway11.1.2.4.0 OAuth User Guide75


7 API Gateway as an OAuth 2.0 resource server

Toregisteranewclientapplication,clicktheNew applicationbutton.

Toeditanexistingclientapplication,clicktheapplicationnameinthelistofapplications.Youcan
addAPIkeys,OAuthcredentials,andOAuthscopesfortheapplication.Formoreinformationon
OAuthscopes,seeManageOAuthscopesonpage76.

Manage OAuth scopes


AnOAuthscopeisatextstringusedtocontrolaccesstoprotectedresources.Theresourcethatthe
scopeisassociatedwithdeterminesthemeaningofthescope.Forexample,ifacustomer_
detailsscopeisassociatedwithaparticularresource,andaclientapplicationisassociatedwith
thecustomer_detailsscope,theclientapplicationwillhaveaccesstothatresource.Client
applicationsandresourcescanhavemultipleOAuthscopes.

Forexample,inthefollowingoverviewdiagram:

l ClientapplicationAcanaccessthecustomer_detailsscope.
l ClientapplicationBcanaccessthecustomer_detailsandphotosscopes.
l ClientapplicationCcanaccessthephotosscopeonly.

Oracle API Gateway11.1.2.4.0 OAuth User Guide76


7 API Gateway as an OAuth 2.0 resource server

YoucanconfigurethescopesthataclientapplicationcanaccessintheClientApplicationRegistry
webinterface.Wheneditingtheclientapplication,selecttheAuthenticationtab.IntheOAUTH
SCOPESsectionyoucanspecifyscopesasfree-formtextorselectascopefromalistofknown
configuredscopes.Youcanalsoselectascopeasadefaultscopefortheclientapplication.Default
scopesareusedwhenanauthorizationortokenrequestdoesnotcontainscopes.Thefulllistof
scopes(defaultandnon-default)representsthelistofscopesthatcanbeincludedinan
authorizationortokenrequest.

Tip Ingeneral,goodOAuthdesigninvolvesafinitenumberofOAuthscopes.Youshould
decideonthesetofscopestobeusedinyoursysteminsteadofcreatingtoomanyscopes
lateron.

Thefollowingfigureshowsthedefaultscopesforaclientapplication:

Note YoucanspecifyanytextstringforanOAuthscope(forexample,customer_detailsor
readonly).

Whenanauthorizationcodeoraccesstokenrequestisreceivedfromaclientapplication,theAPI
GatewayOAuthaccesstokenfilterscheckthatthescopesinthemessagematchthescopes
configuredfortheclientapplication.Ifnoscopesareprovidedinthemessage,thefiltercreatesan
accesstokenforthescopesthatareconfiguredasdefault.Thescopeforwhichtheaccesstoken

Oracle API Gateway11.1.2.4.0 OAuth User Guide77


7 API Gateway as an OAuth 2.0 resource server

wascreatedischeckedagainstthelistofavailablescopesintheClientApplicationRegistryweb
interface.ThislistisgeneratedfromthescopesdefinedintheValidate Access Tokenfilterinthe
serverconfiguration.Formoredetailsonthisfilter,seeValidateaccesstokenonpage80.

Note YoucanalsospecifyOAuthscopesusingselectors(forexample,use
${http.request.verb}tomapHTTPGETandPUTrequests).However,theClient
ApplicationRegistrywebinterfacedoesnotdisplayselectorizedscopesinthelistof
availablescopes.ThisisbecauseselectorizedscopesintheValidate Access Tokenfilter
cannotbeevaluatedatregistrationtime.

Theadministratormustthereforefindoutaboutanyselectorizedscopestobeappliedto
resourcesatruntime.Ifascopemustbeconfiguredusingaselector,theadministrator
mustfindoutexactlywhichselectortospecifyinthescope.Formoredetailsonselectors,
seetheAPIGatewayPolicyDeveloperGuide.

Client Application Registry


Bydefault,OAuthclientapplicationdataisstoredinaKeyPropertyStore(KPS)backedbyan
ApacheCassandradatabase.FormoredetailsonKPSandApacheCassandra,seetheAPIGateway
KeyPropertyStoreUserGuide.

Relational database-backed Client Application


Registry
TheClientApplicationRegistryKPScanalsobebackedbyarelationaldatabasesuchasOracle,
MySQL,IBMDB2,orMicrosoftSQLServer.FormoreinformationonKPSanddatabasestorage,see
theAPIGatewayKeyPropertyStoreUserGuide.

OAuth relational database schemas


YoucanviewtheOAuthrelationaldatabaseschemasbyusingSQLcommands.Forexample,toview
atableinaMySQLdatabase,usethefollowingcommand:

show columns from TABLE_NAME;

TheOAuthtablenamesare:

l oauth_access_token
l oauth_refresh_token
l oauth_authz_code

Data security
IfyouhavesetanencryptionpassphraseforAPIGateway,theOAuthsecretandAPIsecretare
encryptedintheClientApplicationRegistry.

Oracle API Gateway11.1.2.4.0 OAuth User Guide78


7 API Gateway as an OAuth 2.0 resource server

Ifyouchangetheencryptionpassphraseatanypoint,youmustre-encryptthedataintheClient
ApplicationRegistryoryouwillnotbeabletoconnecttotheClientApplicationRegistryweb-based
interface.

Tore-encryptthedata,usethekpsadmintool,andselecttheoptiontoRe-encrypt All.Thisre-
encryptsalldatainalltablesinacollection.Youarepromptedfortheoldpassphrase(neededto
decryptthedata).Thedataisthenre-encryptedwiththecurrentAPIGatewaypassphrase.Repeat
thisprocessforeachKPScollection.

Formoreinformationonthekpsadmintool,seetheAPIGatewayKeyPropertyStoreUserGuide.

Oracle API Gateway11.1.2.4.0 OAuth User Guide79


OAuth 2.0 resource server
filters 8
ThissectiondescribesthefiltersyoucanusewhenAPIGatewayisactingasanOAuthresource
server.Theseinclude:

Filter Description

Validateaccesstokenonpage Validateanaccesstokenandallowaccesstoaprotected
80 resource.

Relatedtopics

l OAuth2.0messageattributesonpage113

Validate access token

Overview
TheOAuth2.0Validate Access Tokenfilterisusedtovalidateaspecifiedaccesstokencontained
inpersistentstorage.OAuthaccesstokensareusedtograntaccesstospecificresourcesinanHTTP
serviceforaspecificperiodoftime(forexample,photosonaphotosharingwebsite).Thisenables
userstograntthird-partyapplicationsaccesstotheirresourceswithoutsharingalloftheirdataand
accesspermissions.

FormoredetailsonsupportedOAuthflows,seeAPIGatewayOAuth2.0authenticationflowson
page17.

General settings
Configurethefollowingfields:

Name:

Enterasuitablenameforthisfilter.

Verify access token is in cache:

Oracle API Gateway11.1.2.4.0 OAuth User Guide80


8 OAuth 2.0 resource server filters

Clickthebrowsebuttontoselectthecacheinwhichtoverifytheaccesstoken( forexample,inthe
defaultOAuth Access Token Store).Toaddanaccesstokenstore,right-clickAccess Token
Stores,andselectAdd Access Token Store.Youcanstoretokensinacache,inarelational
database,orinanembeddedCassandradatabase.Formoredetails,seeManageaccesstokensand
authorizationcodesonpage48.

Location of access token:

Selectoneofthefollowing:

l In Authorization Header with prefix:


TheaccesstokenisintheAuthorizationheaderwiththeselectedprefix.DefaultstoBearer.
Thisisthedefaultoption.
l In query string/form body field named:
TheaccesstokenisintheHTTPquerystringwiththenamespecifiedinthetextbox.
l In Attribute:
TheaccesstokenisintheAPIGatewaymessageattributespecifiedinthetextbox.
Validate Scopes:

SelectwhetherscopesmatchAnyorAlloftheconfiguredscopesinthetable,andclickAddtoadd
anOAuthscope.Thedefaultscopesarefoundin${http.request.uri}.

Forexample,thedefaultscopesusedintheOAuthdemosareresource.READand
resource.WRITE.

Response codes
TheValidate Access Tokenfilterperformsanumberofcheckstodetermineifthetokenisvalid.If
anyofthechecksfail,theresponsecanbeexaminedtodeterminethereasonforthefailure.

Thefilterperformsthefollowingsequenceofstepstodetermineifthetokenisvalid:

1. Locatethetokenintheincomingrequest.ThetokencanbeintheAuthorizationheader,ina
querystring,orinamessageattribute.
l Ifthefilterisconfiguredtofindthetokeninamessageattributeandnotokenisfound,the
followingresponseissent:

HTTP/1.1 400 Bad Request


WWW-Authenticate:Bearer realm="DefaultRealm",
error="invalid_request",
error_description="Unable to find token in the message."

l IfthefilterisconfiguredtofindthetokenintheAuthorizationBearerheaderandnotokenis
found(ortheAuthorizationheaderisnotfoundordoesnotcontaintheBearerheader),the
followingresponseissent:

HTTP/1.1 401 Unauthorized


WWW-Authenticate:Bearer realm="DefaultRealm"

Oracle API Gateway11.1.2.4.0 OAuth User Guide81


8 OAuth 2.0 resource server filters

2. Ifthetokenisfoundintheincomingrequest,nextverifythatthetokencanbefoundintheAPI
Gatewaypersistentstoragemechanism.Ifitcannotbefound,thefollowingresponseissent:

HTTP/1.1 401 Unauthorized


WWW-Authenticate:Bearer realm="DefaultRealm",
error="invalid_token",
error_description="Unable to find the access token in persistent storage."

3. Ifthetokenisfoundinpersistentstorage,nextverifytheauthenticityofthetoken.This
includescheckingthetoken'sexpiry,clientidentifier,andrequiredscopes.
l Checkifthetokenhasexpired.Anexpiredtokenmustnotbeabletoallowaccesstoa
resource.Ifthetokenhasexpired,thefollowingresponseissent:

HTTP/1.1 401 Unauthorized


WWW-Authenticate:Bearer realm="DefaultRealm",
error="invalid_token",
error_description="The access token expired."

l ChecktheclientIDinthetokenandensureitisthesameasaclientIDstoredintheAPI
Gatewayclientregistry.(TouseOAuthyouneedaclientapplicationandtheclient
applicationmusthaveOAuthcredentials.)Checkthattheapplicationisstillenabled.If
eitherchecksfail,thefollowingresponseissent:

HTTP/1.1 401 Unauthorized


WWW-Authenticate:Bearer realm="DefaultRealm",
error="invalid_token",
error_description="The client app was not found or is disabled."

l ValidatethescopesinthetokenagainstthescopesconfiguredinPolicyStudio.InPolicy
StudioyoucanspecifythatscopesshouldmatchAnyorAllofthescopeslistedinthe
table.IfAllisselected,thetokenscopesmustmatchallofthescopeslistedinPolicy
Studio.IfAnyisselected,thetokenscopesintersectionwiththescopeslistedinPolicy
Studiomustnotbeempty.Ifthescopesdonotmatch,thefollowingresponseissent:

HTTP/1.1 403 Forbidden


WWW-Authenticate:Bearer realm="DefaultRealm",
error="insufficient_scope",
error_description="scope(s) associated with access token are not valid to
access this resource.",
scope="Scopes must match Any of these scopes:resource.WRITE"

Themessageincludesafurtherstringlistingthescopesrequiredtoaccesstheresource.
4. Ifthetokenisauthentic,allowaccesstotheresource.

Oracle API Gateway11.1.2.4.0 OAuth User Guide82


API Gateway as an OAuth
2.0 client 9
ThissectiondescribeshowtoconfigureAPIGatewayasanOAuthclient.Itdescribesthefollowing:

l OAuthclientfeaturesofAPIGatewayandasampleOAuthclientworkflowSeeIntroductionto
APIGatewayOAuthclientonpage83.
l HowtosetupAPIGatewayasanOAuthclientSeeSetupAPIGatewayOAuthclientonpage
86.
l HowtoconfigureOAuthclientapplicationcredentialsinAPIGatewaySeeConfigureOAuth
clientapplicationcredentialsonpage86.

Relatedtopics

l OAuth2.0clientfiltersonpage93
l OAuth2.0messageattributesonpage113

Introduction to API Gateway OAuth client


OAuthisanopenstandardforauthorizationthatenablesclientapplicationstoaccessserver
resourcesonbehalfofaspecificresourceowner.OAuthalsoenablesresourceowners(endusers)to
authorizelimitedthird-partyaccesstotheirserverresourceswithoutsharingtheircredentials.

APIGatewaycanactastheclientapplicationinanOAuth2.0scenario,andassuchAPIGatewaycan
instigatetheauthorizationprocess,handleredirects,andrequestOAuthtokensfroman
authorizationserver.Receivedtokensarestoredsecurelyandsubsequentlyusedtoaccessprotected
resourcesonbehalfofusers.Thisprovidesthefollowingbenefits:

l TheOAuthclientburdenismovedtoAPIGateway
l Theresourceowner'scredentialsareneversharedwiththeclientapplication
l Theaccesstokenisneversharedwiththeresourceowner'suseragent
Note Thisdocumentassumesthatyouarefamiliarwithboththetermsandconceptsdescribed
intheOAuth2.0AuthorizationFrameworkandtheOAuthserverfeaturesofAPIGateway
(formoreinformation,seeIntroductiontoAPIGatewayOAuth2.0serveronpage13).

Oracle API Gateway11.1.2.4.0 OAuth User Guide83


9 API Gateway as an OAuth 2.0 client

API Gateway OAuth client features


APIGatewayprovidesthefollowingfeaturestosupportOAuth2.0clientfunctionality:
l ProviderprofilesfordefiningOAuthserviceprovidersandtheapplicationsregisteredwiththem.
l AsetofpreconfiguredsampleproviderprofilesforusewithOracle,Google,andSalesforce
OAuthservices.
l Storageofreceivedtokens.
l SupportforthefollowingOAuthflows:
o Authorizationcodegrant
o Resourceownerpasswordcredentials
o Clientcredentialsgrant
o JWT
o SAMLassertion
Note Theimplicitgranttypeisnotsupportedasitisdesignedtosupportclient
applicationsthatdonothaveasecureservercomponent,andassuchitisnot
applicableforAPIGatewayactingasanOAuthclient.

ThefollowingdiagramshowstheroleofAPIGatewayasanOAuth2.0clientapplicationaccessing
OAuthservicesprovidedbyOracleAPIGateway,Google,andSalesforce:

FormoreinformationonhowtointegrateyourapplicationwithGoogleorSalesforceAPIsusingAPI
GatewayandOAuth2.0,seetheAPIGatewayGoogleOAuth2.0IntegrationGuideandtheAPI
GatewaySalesforceOAuth2.0IntegrationGuide.

Oracle API Gateway11.1.2.4.0 OAuth User Guide84


9 API Gateway as an OAuth 2.0 client

OAuth 2.0 example client workflow


ThisexampleissimilartotheOAuthserverexampleworkflowonpage14,butinthiscontextAPI
Gatewayactsasaclient,andtheserviceproviderisGoogle.

Assumethatyou,asaresourceowner,areusingaservicethatwantstoaccessyourGooglecalendar
(aprotectedresource).TheserviceisdefinedonAPIGateway(APIGatewayisanOAuthclient).You
donotwanttorevealyourGooglecredentialstoAPIGateway.Thisproblemcanbesolvedusingthe
exampleOAuth2.0webserverflowshowninthefollowingdiagram:

Outofband,APIGatewaypreregisterswithGoogleandobtainsaclientIDandsecret.APIGateway
alsoregistersacallbackURLtoreceivetheauthorizationcodefromGooglewhenyou,asresource
owner,authorizeaccesstoyourGooglecalendar.Theapplicationhasalsorequestedaccesstoan
APInamed/google/calendar,whichhasanOAuthscopeofcalendar.

ThecredentialsreceivedfromGoogleareaddedtotheGoogleOAuthproviderprofileusingPolicy
Studio(formoreinformation,seeConfigureOAuthclientapplicationcredentialsonpage86).The
providerprofileisalsoconfiguredwiththeauthorizationendpointandtokenendpointofthe
Googleauthorizationserver.ThecallbackURLisalsocreatedasanHTTPlisteneronAPIGateway,
withafilterforreceivingtheauthorizationcode.

Thestepsinthediagramaredescribedasfollows:

1. Usingabrowserormobilephone,youaccessaservicedefinedonAPIGateway,whichneedsto
accessyourGooglecalendaronyourbehalf.Theclientapplicationinitiatestheauthorization

Oracle API Gateway11.1.2.4.0 OAuth User Guide85


9 API Gateway as an OAuth 2.0 client

flowbyredirectingyourbrowsertotheauthorizationendpointdefinedintheGoogleOAuth
providerprofile.
2. AfterfollowingtheredirectyoulogintoyourGoogleaccountandauthorizetheapplicationfor
therequestedscope.
Note YouhavenotsharedyourGoogleusernameandpasswordwiththeAPIGateway
application.Atthispoint,you,astheresourceowner,arenolongerinvolvedin
theprocess.

3. TheauthorizationserverthenredirectsyourbrowsertothecallbackURLonAPIGateway,along
withanauthorizationcode.
4. TheAPIGatewayclientapplicationgetstheauthorizationcode,andmustexchangethisshort-
livedcodeforanaccesstoken.Theclientapplicationsendsanotherrequesttothe
authorizationserver,thistimetothetokenendpoint,sayingithasacodethatprovestheuser
hasauthorizedittoaccesstheircalendar,andnowissuetheaccesstokentobesentontothe
API(resourceserver).Theauthorizationserververifiestheauthorizationcodeandreturnsan
accesstoken.
5. TheclientapplicationsendstheaccesstokentotheAPI(resourceserver),andreceivesthe
calendarinformationasrequested.

Set up API Gateway OAuth client


APIGatewayincludesanumberofsampleclientapplications.Youcandeploythesample
applicationsusingthedeployOAuthConfig.pyscriptoryoucanimportthemmanually.

l FormoreinformationonusingthedeployOAuthConfig.pyscript,seeEnableOAuth
managementonpage43.
l Formoreinformationonimportingthemmanually,seeImportsampleclientapplicationson
page45.

Configure OAuth client application


credentials
OAuth2.0clientcredentialprofilesenableyoutogloballyconfigureauthenticationsettingsfor
OAuth2.0asaclient.AnOAuth2.0credentialprofileisthecombinationofOAuthserviceprovider
detailsandaspecificOAuthclientapplication.AnOAuthserviceproviderdefinestheauthorization
andtokenendpoints.APIGatewayincludesthefollowingpreconfiguredOAuthproviders:

l APIGateway
l Google
l SalesForce
ClientapplicationsmustberegisteredwiththeserviceprovidertoobtainaclientIDandsecretas
wellastoregisteradditionaldetailsliketheOAuthflowtypeandredirectURL(whererequired).

Oracle API Gateway11.1.2.4.0 OAuth User Guide86


9 API Gateway as an OAuth 2.0 client

l Googleapplicationscanberegisteredathttps://cloud.google.com/console
l SalesForceapplicationscanberegisteredathttps://www.salesforce.com
l APIGatewayapplicationscanberegisteredintheClientApplicationRegistry(port8089).
TheAPIGatewayproviderrepresentsOAuthservicesrunningonanAPIGateway.Formore
informationonsettinguptheOAuthserveronAPIGateway,seeSetupAPIGatewayasanOAuth2.0
serveronpage43.TheAPIGatewayproviderusestheexistingOAuthserversamplesfor
authorizationandtokenendpoints(forexample,
https://127.0.0.1:8089/api/oauth/authorizeand
https://127.0.0.1:8089/api/oauth/token).TheGoogleandSalesForceprovidersettings
shipwiththecurrentpublicendpoints.

YoucanaccessthepreconfiguredOAuthprovidersandaddclientapplicationcredentialsunderthe
External ConnectionsnodeinthePolicyStudiotree.YoucanalsoaddnewOAuthproviders.See
AddOAuthprovideronpage91formoreinformation.

Add application credentials


EachOAuth2.0providercanhavemultipleclientapplicationcredentials.Eachsetofcredentials
representsanapplicationthathasbeenregisteredwiththeprovider.Uponregistering,the
applicationisassignedaclientIDandsecretandcandesignatearedirectURLforreceivingaccess
codes.

ToaddanapplicationforanexistingOAuth2.0provider,clickanOAuth2.0clientcredentialnode
(forexample,Google),andclicktheAddbuttonontheOAuth2 CredentialstaboftheOAuth2
Credential Profilewindow.CompletethefollowingfieldsontheAdd OAuth2 Application
dialog:

Name:
Enterasuitablenameforthisclientapplication.

Client ID:
ThisidentifiestheclientresponsiblefortheOAuthrequest.ThisIDisassignedbytheOAuth
provider.

Client Secret:
Thisisaconfidentialsecretkeyusedforauthentication.ThissecretisassignedbytheOAuth
provider.

OAuth Flow Type:


SelectanOAuthflowtype.Theoptionsare:

l AuthzCode
l ClientCredentials
l JWT
l ResourceOwner
l SAML
FormoredetailsontheauthenticationflowsthatAPIGatewaysupports,seeAPIGatewayOAuth2.0
authenticationflowsonpage17.

Oracle API Gateway11.1.2.4.0 OAuth User Guide87


9 API Gateway as an OAuth 2.0 client

Redirect URL:
EntertheURLoftheclient'sredirectendpoint(forexample,https://localhost:8088/oauth_
callback).ThisistheURLregisteredwiththeproviderforreceivingaccesscodesviaaredirect
fromtheauthorizationserver.ThismustmatchalistenerconfiguredonAPIGateway(seeCreatea
callbackURLlisteneronpage91).

Toconfigureclientscopes,SAMLbearersettings,JWTsettings,orotheradvancedsettings,clickthe
appropriatetabs.

Configure scopes
YoucanconfigurethescopesthataclientapplicationcanaccessontheScopestab.ClickAddto
addascope.Thisisthesetofscopesrequiredbytheapplication,andthislistmustmatch,orbea
subsetof,therequiredscopesregisteredwiththeOAuthprovider.Formoreinformationonscopes,
seeManageOAuthscopesonpage76.

Configure SAML bearer


YoucanconfigureSAMLbearersontheSAML Bearertab.AccordingtotheIETFdraftdocument
SAML2.0ProfileforOAuth2.0,aSAMLassertioncanbeusedtorequestanaccesstokenwhena
clientwishestoutilizeanexistingtrustrelationship,expressedthroughthesemanticsoftheSAML
assertion,withoutadirectuserapprovalstepattheauthorizationserver.Whenaclientapplicationis
configuredtousetheSAMLgranttypeaSAMLassertionmustbeeitherconfigured/generatedor
madeavailableonthemessageboard.

TogenerateanassertionselecttheGenerate assertion using following configurationoption


andcompletethefollowingfields:

Use private key to sign SAML assertion:


ClickSigning Keytoselectaprivatekeytousetosigntheassertion.Thiswillbetheprivatekey
certificateregisteredwiththeOAuthprovider.

Resource Owner ID:


Entertheidentityoftheresourceownerasexpectedbytheresourceserver.Thiscanbespecified
usingaselector(forexample,${authentication.subject.id}).

Assertion expires in:


Enterthetimedurationthattheassertionisvalidfor.Expressedindays,hours,minutes,and
seconds.

Drift time (secs):


Enteradrifttimeinsecondstoallowforclockskew.

Alternatively,youcangeneratetheassertionthroughothermeansandtakeitfromthemessage
boardbyselectingtheoptionGet assertion from message attribute namedandenteringthe
nameoftheattribute(forexample,${oauth.saml.assertion}).

Note TheIETFdraftdocumentalsodescribeshowtouseSAML2.0forclientauthentication.
ThisisnotsupportedinAPIGateway.

Oracle API Gateway11.1.2.4.0 OAuth User Guide88


9 API Gateway as an OAuth 2.0 client

TheAPIGatewayusesaSAMLtemplatetogeneratetheSAMLassertion.Thetemplatefileisstored
undertheResources/StylesheetsdirectoryinPolicyStudiowhenthedeployOAuthConfig
scriptisexecuted(seeEnableOAuthmanagementonpage43).Alternatively,youcanfindthisfile
in$VDISTDIR/samples/oauth/templates/samltemplate.xmlandimportitviaPolicy
Studio.AtruntimethevaluesinthetemplatearesubstitutedwithvaluesconfiguredfortheOAuth
clientSAMLapplication.

Configure JWT
YoucanconfigureJWTontheJWTtab.ThisenablesyoutoconfigureJWTforauthorizationgrant,
asdefinedbytheIETFdraftdocumentJSONWebToken(JWT)ProfileforOAuth2.0Client
AuthenticationandAuthorizationGrants.

Note APIGatewayonlysupportstheuseofJWTasauthorizationgrantanddoesnotsupport
JWTforclientauthentication.

Configurethefollowingfields:

Sign using private key:


SelectthisoptionandclickSigning Keytoselectaprivatekeycertificatethathasbeenregistered
withtheOAuthprovider,anduseittosigntheJWTclaim.

Sign using client secret:


SelectthisoptiontosigntheJWTclaimusingaclientsecretissuedbytheOAuthprovider.

JWT expiry (in secs):


EntertheexpirytimefortheJWTclaim,inseconds.

Add additional JWT claims:


ClicktheAddbuttontoaddadditionalJWTclaims.YoucanalsoEditorDeleteexistingclaims.

BydefaultaJWTisgeneratedwiththefollowingclaimset:

Claim Default value

iss TheapplicationclientID.

aud Thetokenendpointoftheprovider.

exp TheexpirytimefromthefieldJWT expiry (in secs).

iat Theissuedassertiontime,thetimetheassertionwasissuedmeasuredinsecondssince
00:00:00UTC,January1,1970.

Theseclaimscanbeoverriddenorextendedbyaddingadditionalclaims.Itisalsopossibletoadd
claimslikescopetodefinescopes,andprn(forSalesForce),orsub(asdefinedintheIETFdraft
document)toidentifytheresourceownerforwhomatokenisbeingrequested.Servicedefined
claimsmustalsobeaddedhere.Unrecognizedclaimsshouldbeignoredbyserviceproviders.

Oracle API Gateway11.1.2.4.0 OAuth User Guide89


9 API Gateway as an OAuth 2.0 client

Claim Default value

sub ThesubjectIDoftheresourceowner.Thisidentifiestheresourceownerforwhomthe
requestisbeingmade.Thepropertyprncanalsobeusedhereforsomeproviders(for
example,SalesForce),buttheuseofthispropertyhasbeensupersededbysubinthe
IETFspecification.

scope Aspacedelimitedlistofscopeswithintheclaim,definingtherequiredpermissionsof
therequest.

Note Scopesmustbeaddedtoaclaimonthistabiftheyarerequiredbytheprovidertobe
presentinaclaim.ThescopesdefinedontheScopestabareaddedtothequerystringof
thetokenrequest,butforflexibilitytheyarenotautomaticallyaddedtotheclaim.The
reasonforthisisbecauseJWTauthorizationgrantsarenon-normativeandclaimsetsmust
beagreedinadvancewithindividualOAuthproviders.Forexample,SalesForcedoesnot
allowtheadditionofscopestoaJWTclaim,whereasGooglerequiresascopeclaim.
AutomaticallyaddingscopesfromtheScopestabtoaclaimcouldprecludeaJWTgrant
flowwherescopesmustbepresentintherequestbutnottheclaim.

Configure advanced settings


Youcanusethefollowingoptionstospecifywheretoaddtheclientcredentialsintokenrequests
(theauthorizationheaderorthequerystring).Thisoptionappliestoallstandardgranttypes
excludingJWTandSAML.

In Authorization Header:
Selectthisoptiontoaddtheclientcredentialstotheauthorizationheader.

In Query String:
Selectthisoptiontoaddtheclientcredentialstothequerystring.

Usethefollowingoptionstospecifywheretofindresourceownercredentials,fortheresource
ownergranttype.

Resource Owner ID:


EntertheresourceownerID.Thiscanbespecifiedasaselector.

Resource Owner Password:


Entertheresourceownerpassword.Thiscanbespecifiedasaselector.

Finally,inthePropertiestableyoucanaddadditionalpropertiestopasswithauthorizationor
tokenrequests.Thesepropertiescanbeusedtosetupprovider-specificoptions,forexample,
Googleauthorizationrequestsrequiretheparameteraccess_type=offlinetoissuearefresh
token.

AfteryouhaveconfiguredyourOAuth2.0clientcredentialsglobally,youcanselecttheclient
credentialprofiletouseforauthenticationontheAuthenticationtabofyourfilter(forexample,in
theConnectionandConnect To URLfilters).Formoreinformation,seetheAPIGatewayPolicy
DeveloperGuide.

Oracle API Gateway11.1.2.4.0 OAuth User Guide90


9 API Gateway as an OAuth 2.0 client

Add OAuth provider


ToconfigureanewOAuth2.0provider,right-clickOAuth2,andselectAdd OAuth2 Client
Credential.CompletethefollowingfieldsontheOAuth2 Provider Configurationdialog:

Profile Name:
EnterasuitablenameforthisOAuthproviderconfiguration(forexample,GoogleorMicrosoft).

Authorization Endpoint:
EntertheURLoftheOAuthprovider'sauthorizationendpoint(forexample,
https://accounts.google.com/o/oauth2/auth).ThisisapublicURLwherearesource
ownerisdirectedtoauthorizeaclientapplication.Thisisusedintheauthorizationcodeflow.

Token Endpoint:
EntertheURLoftheOAuthprovider'stokenendpoint(forexample,
https://accounts.google.com/o/oauth2/token).ThisisapublicURLwhereaclient
applicationcanrequestatoken.

Token Store:
Clickthebrowsebuttontochooseanaccesstokenstore.Thisiswherereceivedtokensarepersisted.

YoucanconfigureOAuthaccesstokenstoresgloballyundertheLibrariesnodeinthePolicyStudio
tree.ThesecanthenbeselectedintheAccess Token Storefield.Formoredetailsonconfiguring
accesstokenstores,seeManageclientaccesstokensonpage91.

Store OAuth State in this Cache:


Clickthebrowsebuttontochooseacache.Thisiswherethestateofanauthorizationrequestis
stored.Thisisusedintheauthorizationcodeflowtomaintainstatewhentheuserisdirectedtothe
authorizationserverforauthorization.

Tip TochangetheconfigurationofanexistingOAuth2.0provider,clicktheOAuthclient
credentialnode,andeditthesettingsontheOAuth2 Provider Settingstabofthe
OAuth2 Credential Profilewindow.

Create a callback URL listener


ThecallbackURLthatisregisteredwithanOAuthproviderisimplementedverysimplybycreatinga
matchingrelativepathinanHTTPlistener.ThepolicyforthispathneedsonlytoaddaRedirect
resource owner to Authz Serverfilter(seeRedirectresourceownertoauthorizationserveron
page95).Thefiltermustbeconfiguredwithareferencetotherelevantproviderprofileforthis
callbackURL.

Manage client access tokens


YoucanconfigureclientaccesstokenstoresundertheLibraries > OAuth2 Storesnodeinthe
PolicyStudiotreeview.APIGatewaycanstoreclientaccesstokensinitscache,inanembedded
database,orinarelationaldatabase.Formoreinformationonthepersistentstorageoptions,see
Manageaccesstokensandauthorizationcodesonpage48.

Oracle API Gateway11.1.2.4.0 OAuth User Guide91


9 API Gateway as an OAuth 2.0 client

Tostoreclientaccesstokensinarelationaldatabase,usetheSQLscriptin
$VDISTIR\system\conf\sql\DBMS_TYPE\oauth-client.sqltocreatethesupporting
schema.TheOAuthclienttablenamesare:

l oauth_client_access_token
l oauth_client_token_props
l oauth_client_refresh_token
OAuthclientaccesstokensarepurgedonexpiry.AfterasuccessfultokenrequesttheOAuthclient
accesstoken(andpotentiallyarefreshtoken)arestoredinpersistentstorage.OAuthauthorization
serversusuallyreturnanexpirywiththeaccesstoken,otherwisethedefaultexpiryof3600seconds
isused.Anexpiryisnotusuallyreturnedwitharefreshtoken,butadefaultexpiryof30daysis
used.YoucanaltertheseexpirysettingsintheClient Token Cleanup Settingssectionofthe
clientaccesstokenstore.

Note Forclientaccesstokenstoresbackedbyadatabase,youcanconfigurethePurge
expired tokensfieldtoperformapurge(forexample,runaquerytoremovetokens)ata
specifiedinterval.

Oracle API Gateway11.1.2.4.0 OAuth User Guide92


OAuth 2.0 client filters
10
ThissectiondescribesthefiltersyoucanusewhenAPIGatewayisactingasanOAuthclient.These
include:

Filter Description

DeleteanOAuthclientaccesstokenon Deleteaclientaccesstoken.
page93

GetOAuthclientaccesstokenonpage Requestaclientaccesstoken.
94

Redirectresourceownerto Redirectaresourceownertoanauthorizationserver
authorizationserveronpage95 tograntordenyaccesstoaresource.

RefreshanOAuthclientaccesstoken Refreshaclientaccesstoken.
onpage96

RetrieveOAuthclientaccesstokenfrom Retrieveapreviouslystoredclientaccesstoken.
tokenstorageonpage97

SaveanOAuthclientaccesstokenon Saveaclientaccesstoken.
page98

Relatedtopics

l OAuth2.0messageattributesonpage113

Delete an OAuth client access token

Overview
YoucanusetheDelete an OAuth Client TokenfiltertoexplicitlydeleteanOAuthclientaccess
token,orrefreshtoken,orboth.

Thisfilterrequiresthemessageattributeoauth.client.applicationtodetermineifthe
applicationhasanaccesstoken,orrefreshtoken,orboth.Thefilterreturnsfalseiftherequired
messageattributeisnotsetorifthereisaproblemremovinganaccessorrefreshtokenfromtoken
storage.

Oracle API Gateway11.1.2.4.0 OAuth User Guide93


10 OAuth 2.0 client filters

General settings
ConfigurethefollowinggeneralsettingfortheDelete an OAuth Client Tokenfilter:

Name:
Enterasuitablenameforthisfilter.

Get OAuth client access token

Overview
YoucanusetheGet OAuth Access Tokenfiltertorequestatoken.Thisfilterattemptstogetthe
accesstokenfrompersistentstorage,andifatokenisnotavailableitsendsanoutboundtoken
request.

General settings
ConfigurethefollowinggeneralsettingsfortheGet OAuth Access Tokenfilter:

Name:
Enterasuitablenameforthisfilter.

Choose OAuth Token Key:


Enterthemessageattributetobeusedasthekeytolookupthetoken.Defaultsto
${authentication.subject.id}.

Ifnokeyisspecifiedinthisfield,theaccesstokenisnotsaved.Thisistoaccommodateanonymous
useofOAuthwherebytheuserstartingtheprocessdoesnotneedtoauthenticatewithAPIGateway
first.

Optionally select a client credential profile:


SelectthisoptionandclickthebrowsebuttontoselectanOAuthclientcredentialprofile.Thiscan
beusedifnoprecedingfilterhassettheapplicationprofileonthemessageboard,ortooverridethe
existingapplicationprofile.

SSL settings
YoucanconfigureSSLsettings,suchastrustedcertificates,clientcertificates,andciphersonthe
SSLtab.Fordetailsonthefieldsonthistab,seetheConnect to URLfilterintheAPIGateway
PolicyDeveloperGuide.

Oracle API Gateway11.1.2.4.0 OAuth User Guide94


10 OAuth 2.0 client filters

Additional settings
TheSettingstaballowsyoutoconfigurethefollowingadditionalsettings:

l Retry
l Failure
l Proxy
l Redirect
l Headers
Bydefault,thesesectionsarecollapsed.Clickasectiontoexpandit.

Fordetailsonthefieldsonthistab,seetheConnect to URLfilterintheAPIGatewayPolicy
DeveloperGuide.

Redirect resource owner to authorization


server

Overview
ThepurposeoftheRedirect resource owner to Authz Serverfilteristoredirecttheresource
owner'suseragenttotheOAuthauthorizationserver.Thisfiltercanonlybeusedinthe
authorizationcodeflow.

General settings
ConfigurethefollowinggeneralsettingsfortheRedirect resource owner to Authz Server
filter:

Name:
Enterasuitablenameforthisfilter.

Choose OAuth Token Key:


Enterthemessageattributetobeusedasthekeytolookupthetoken.Thetokenkeymustbesetto
theauthenticationvalueyourequirefortheOAuthtoken.InthecontextofanOpenIDConnectflow
theOAuthtokenkeycanbeacookievalue.Defaultsto${authentication.subject.id}.

Ifnokeyisspecified,thisfieldisignored.ThisistoaccommodateanonymoususeofOAuth
wherebytheuserstartingtheprocessdoesnotneedtoauthenticatewithAPIGatewayfirst.

Override scopes setup for authz request:


Thisfieldallowsyoutooverridethescopesassignedtoaclientprofile.Thiscouldpotentiallybe

Oracle API Gateway11.1.2.4.0 OAuth User Guide95


10 OAuth 2.0 client filters

usedintheOpenIDConnectflowwherebyyoucouldspecifyscopesfortheOpenIDConnectflow,
orifyoualreadyhaveasessionyouwouldnotneedtospecifyOpenIDConnectscopes.(Foran
example,seetheOAuthclientdemo.)

Optionally select a client credential profile:


SelectthisoptionandclickthebrowsebuttontoselectanOAuthclientcredentialprofile.Thiscan
beusedifnoprecedingfilterhassettheapplicationprofileonthemessageboard,ortooverridethe
existingapplicationprofile.

Configure OAuth State Map:


ThisallowsyoutoconfigureextraparametersintheOAuthstatemap(forexample,toimplement
cross-siterequestforgery(CSRF)protection).Bydefaultthestatemapcontainsclient_idand
oauth.token.id.Anyextraparametersaddedhereareaddedtothestatemap.Themessage
attributeoauth.state.mapwillbeavailableatthecallbackendpointwhenanauthorizationcode
isexchangedforatoken.

Selectoneofthefollowingoptions:
l Add extra state properties:
ClickAddtostoreadditionalstateproperties,andentertheNameandValueinthedialog.
l Retrieve properties from selector:
Entertheattributethatstorestheproperties.Defaultstooauth.state.map.

Refresh an OAuth client access token

Overview
OAuth2.0clienttokensaredesignedtobeshortlivedandhaveanexpirytime,however,tokenscan
beissuedwithrefreshtokens.Ifatokenhasexpired,andithasarefreshtoken,youcanusethe
Refresh an OAuth Client Access Tokenfiltertoexplicitlyrefreshthetoken.Thisfilterlooksup
thetokenandchecksforarefreshtoken.Ifitfindsarefreshtoken,thefiltersendsanoutbound
refreshtokenrequesttotheOAuthauthorizationservertoobtainanewaccesstoken(andpossiblya
newrefreshtoken).

General settings
ConfigurethefollowinggeneralsettingsfortheRefresh an OAuth Client Access Tokenfilter:

Name:
Enterasuitablenameforthisfilter.

Choose OAuth Token Key:


Enterthemessageattributetobeusedasthekeytolookupthetoken.Defaultsto
${authentication.subject.id}.

Oracle API Gateway11.1.2.4.0 OAuth User Guide96


10 OAuth 2.0 client filters

Optionally select a client credential profile:


SelectthisoptionandclickthebrowsebuttontoselectanOAuthclientcredentialprofile.Thiscan
beusedifnoprecedingfilterhassettheapplicationprofileonthemessageboard,ortooverridethe
existingapplicationprofile.

SSL settings
YoucanconfigureSSLsettings,suchastrustedcertificates,clientcertificates,andciphersonthe
SSLtab.Fordetailsonthefieldsonthistab,seetheConnect to URLfilterintheAPIGateway
PolicyDeveloperGuide.

Additional settings
TheSettingstaballowsyoutoconfigurethefollowingadditionalsettings:

l Retry
l Failure
l Proxy
l Redirect
l Headers
Bydefault,thesesectionsarecollapsed.Clickasectiontoexpandit.

Fordetailsonthefieldsonthistab,seetheConnect to URLfilterintheAPIGatewayPolicy
DeveloperGuide.

Retrieve OAuth client access token from


token storage

Overview
YoucanusetheRetrieve OAuth Client Access Token from Token Storagefiltertoretrievea
storedaccesstokenfromaclientaccesstokenstore.

TokensreceivedfromOAuthprovidersarestoredinaClient Access Token Store.Youcan


configureclientaccesstokenstoresundertheLibraries > OAuth2 StoresnodeinthePolicy
Studiotreeview.SimilartoanAccess Token Store,thisstorecanbebackedbyanAPIGateway
cache(default),arelationaldatabase,ortheembeddedApacheCassandradatabase.(Formore
detailsonclientaccesstokenstores,seeManageclientaccesstokensonpage91.)

AconfiguredtokenstoreisassociatedwithanOAuthprovider(seeAddOAuthprovideronpage91)
andissharedbyallclientapplicationsregisteredwiththatprovider.

Oracle API Gateway11.1.2.4.0 OAuth User Guide97


10 OAuth 2.0 client filters

ThesestoredtokenscanberetrievedbythisfilterbyspecifyingtheOAuth2.0providerprofile(the
clientapplicationregisteredwithaprovider)andthetokenkey(forexample,theauthentication
subjectidofthecurrentuser).StoredtokensareindexedbytheclientIDofthetheclient
applicationandthetokenkey.Ifauthentication.subject.idisnotavailable,theclientIDis
usedforbothindexes.Thisisvalidforgranttypesthattreattheclientapplicationastheresource
owner,thatis,clientcredentials,JWT,andSAML(whennoresourceownerisspecified).

Ifavalidtokenisfoundbythisfilteritisplacedonthemessageboardas
oauth.client.accesstoken,andthefilterpasses.Ifthetokenisexpired,orthereisnotoken
found,thefilterfails(expiredtokensarestillplacedonthemessageboard).Thefailpathcanbe
usedtorefreshanexpiredtokenorstarttheprocessofrequestingatoken.Theclientapplicationis
alsoplacedonthemessageboard,undertheattributenameoauth.client.application,for
useinsubsequentfilters.

General settings
ConfigurethefollowinggeneralsettingsfortheRetrieve OAuth Client Access Token from
Token Storagefilter:

Name:
Enterasuitablenameforthisfilter.

Choose OAuth Token Key:


Enterthemessageattributetobeusedasthekeytolookupthetoken.Defaultsto
${authentication.subject.id}.

Choose profile to be used for token request:


ClickthebrowsebuttontoselectanOAuth2.0clientcredentialprofile.

Save an OAuth client access token

Overview
YoucanusetheSave an OAuth Client Tokenfiltertosaveatokenwithadifferenttokenkey.
Thisfiltercanfailif:

l Thetokenhasnotokenkey
l Thetokenhasnoapplication
l Thetokenkeyisthesamekeythatwasalreadystoredfortheapplication
l Thereisaproblemsavingthetokentopersistentstorage

General settings
ConfigurethefollowinggeneralsettingsfortheSave an OAuth Client Tokenfilter:

Oracle API Gateway11.1.2.4.0 OAuth User Guide98


10 OAuth 2.0 client filters

Name:
Enterasuitablenameforthisfilter.

Choose OAuth Token Key:


Enterthemessageattributetobeusedasthetokenkey.Defaultsto
${authentication.subject.id}.

Oracle API Gateway11.1.2.4.0 OAuth User Guide99


API Gateway and OpenID
Connect 11
ThissectiondescribeshowtoconfigureAPIGatewayasanOpenIDConnectidentityprovider(IdP)
andasanOpenIDConnectrelyingparty(RP).Itdescribesthefollowing:

l OpenIDConnectfeaturesofAPIGatewaySeeIntroductiontoAPIGatewayOpenIDConnecton
page100.
l SampleOpenIDConnectworkflowSeeOpenIDConnectflowonpage104.
l HowtosetupAPIGatewayasanOpenIDConnectserverSeeBuildanOpenIDConnectIdP
serveronpage105.
l HowtosetupAPIGatewayasanOpenIDConnectclientSeeBuildanOpenIDConnectclient
onpage105.
l HowtousetheclientdemoforanOpenIDConnectflowSeeUsetheAPIGatewayOAuthclient
demo onpage106.

Relatedtopics

l OpenIDConnectfiltersonpage110
l OAuth2.0messageattributesonpage113

Introduction to API Gateway OpenID


Connect
TheOpenIDConnect1.0(OID)protocolisasimpleidentitylayerontopoftheOAuth2.0protocol.
OAuth2.0providesanaccessauthorizationdelegationprotocol,andOpenIDConnectleverages
OAuthfeaturestoallowauthorizedaccesstouserauthenticationsessionAPIsinaninteroperable
manner.OpenIDConnectusesaRESTinterfaceandsimpleJSONassertionscalledJSONWebTokens
(JWTs)toprovideidentifyingclaimsaboutusers.TheprotocolisdesignedtobeAPI-friendlyand
adaptabletomultipleformatssuchaswebandmobile,andithasbuilt-inprovisionsforrobust
signingandencryption.

InitssimplestformanOpenIDConnectdeploymentallowsapplications(suchasbrowsers,mobiles,
anddesktopclients),torequestandreceiveinformationabouttheidentitiesofauser.Thisallows
theusertoauthenticatetoathird-partyapplicationthatactsasarelyingparty(RP)usinganidentity
establishedwiththeOpenIDConnectidentityprovider(IdP).

Oracle API Gateway11.1.2.4.0 OAuth User Guide100


11 API Gateway and OpenID Connect

ThissectiondescribestheconceptsbehindOpenIDConnectanddemonstrateshowtousetheAPI
GatewayasanOpenIDConnectidentityproviderandasarelyingparty.Thefollowingsectionsuse
theclientdemothatshipswithAPIGatewaytoillustrateOpenIDConnectconcepts(seeUsetheAPI
GatewayOAuthclientdemo onpage106).

OpenID Connect concepts


OpenIDConnectisspecifiedintheOpenIDConnect1.0specification.Itdefinesthefollowing
concepts:
l Claim:Apieceofinformationaboutanauthenticateduser(forexample,emailorphone
number).
l Relyingparty(RP):OAuth2.0clientapplicationrequiringend-userauthenticationandclaims
fromanOpenIDConnectidentityprovider.APIGatewaycanactasarelyingpartyconsuming
servicesfromathirdpartysuchasGoogle.
l Identityprovider(IdP):OAuth2.0authorizationserverthatiscapableofauthenticatingtheend-
userandprovidingclaimstoarelyingpartyabouttheenduser.APIGatewaycanactasan
identityproviderforrelyingparties.
l IDtoken:JSONWebToken(JWT)thatcontainsclaimsabouttheauthenticateduser.
l UserInfoendpoint:Protectedresourcethat,whenpresentedwithanaccesstokenbytheclient,
returnsauthorizedinformationabouttheenduser.

Relationship to OAuth 2.0


TosupportmaximuminteroperabilitytheOIDspecificationdefinesstandardscopes,definedrequest
objectsandcorrespondingclaims,theIDtokenformat,andaUserInfoendpoint.Thesefeatures
representtheprimaryadditionstotheOAuth2.0standardandshouldbeavailableacrossallIdP
implementationsofOpenIDConnect.

Oracle API Gateway11.1.2.4.0 OAuth User Guide101


11 API Gateway and OpenID Connect

Standard scopes
TheOpenIDConnectspecificationdefinesasetofpredefinedscopesforuseintheOpenIDConnect
authorizationflow.

l openidREQUIRED.InformstheauthorizationserverthattheclientismakinganOpenID
Connectrequest.ThisistheonlyscopedirectlysupportedintheOpenIDConnectfilters.Ifthe
openidscopeisnotpresentinanauthorizationrequesttheOpenIDConnectCreate ID Token
filterpasses,leavingthemessageunmodified.Whenitispresent,andtherequestisvalid,theID
tokenassociatedwiththeauthenticationsessionisreturned.Iftheresponse_typeincludes
token,theIDtokenisreturnedintheauthorizationresponsealongwiththeaccesstoken.Ifthe
response_typeincludescode,theIDtokenisreturnedaspartofthetokenendpoint
response.
ThefollowingscopesarenotdirectlycateredforintheOpenIDConnectfilters,butaremade
availableonthemessagesothatpolicydeveloperscancorrectlyrespondtotheminpolicies.They
differtoOAuth2.0scopesinthattheydonotneedtobeexpresslyassociatedwitharesourceor
API,andareautomaticallyconsideredvalidscopesforclientapplications.However,thesescopes
canbeconsideredregularOAuth2.0scopeswhenaccessingtheUserInfoendpoint,andiftheyare
presentintheaccesstoken,policydeveloperscanconstructanappropriateclaimsresponse.

l profileOPTIONAL.Thisscoperequeststhattheissuedaccesstokengrantsaccesstotheend
usersdefaultprofileclaims(excludingtheaddressandemailclaims)attheUserInfo
endpoint.Theprofileclaimscaninclude:name,family_name,given_name,middle_name,
nickname,preferred_username,profile,picture,website,gender,birthdate,
zoneinfo,locale,andupdated_at.
l emailOPTIONAL.Thisscoperequeststhattheissuedaccesstokengrantsaccesstotheemail
andemail_verifiedclaimsattheUserInfoendpoint.

Oracle API Gateway11.1.2.4.0 OAuth User Guide102


11 API Gateway and OpenID Connect

l addressOPTIONAL.Thisscoperequeststhattheissuedaccesstokengrantsaccesstothe
addressclaimattheUserInfoendpoint.
l phoneOPTIONAL.Thisscoperequeststhattheissuedaccesstokengrantsaccesstothe
phone_numberandphone_number_verifiedclaimsattheUserInfoendpoint.

Request object and claims


TheOpenIDConnectrequestobjectisanoptionalpartofthespecificationandisnotsupportedin
thecurrentversionofAPIGateway.TherequestobjectisusedtoprovideOpenIDConnectrequest
parametersthatmightdifferfromthedefaultones.Requestobjectsmightbesupportedinfuture
versionsofAPIGateway.

ID token
TheIDtokenisaJWT-basedsecuritytokenthatcontainsclaimsabouttheauthenticationofanend
userbyanauthorizationserver.WhenusingtheauthorizationcodeflowtheIDtokenisreturnedas
apropertyoftheaccesstoken.FortheimplicitandsomehybridflowstheIDtokenisreturnedin
responsetotheauthorizationrequest.AsanIdPAPIGatewaywillproduceanIDtokenusingthe
Create ID Tokenfilter,eitherintheauthorizationendpointpolicyorthetokenendpointpolicy.
Thistokenwillbesignedforverificationbytheclientandcanincludeuserdefinedclaims.This
providesflexibilityincreatingclaimsfromanyuserstore.ActingasanRP,aclientcanverifya
receivedIDtokenwiththeVerify ID Tokenfilter.ThisshouldbedoneinthecallbackpolicyasAPI
Gatewaydoesnotsupportimplicitflowsasaclient.Afterbeingverified,theIDtokencanbeusedto
lookuporcreateauserrecordandcreateanauthenticatedsessionfortheuser.

UserInfo endpoint
TheUserInfoendpointisdefinedasanOAuth2.0protectedresourcethatreturnsextendedclaims
abouttheauthenticatedenduser.ToaccessthisresourceanAPIGatewayactingasanRPmustuse
theaccesstokenreceivedintheOpenIDConnectauthenticationprocess.Asuccessfulrequestwill
returnaJSONobjectwiththeclaimsfortheuser.AsanIdPtheimplementationoftheUserInfo
endpointshouldbesimilartoanyOAuthprotectedresourcewithaminimumscoperequirementof
openid.Theimplementationofthisendpointisdeliberatelyleftopenforpolicydevelopersto
integratetheirownauthenticationstores.

Prerequisites
TousetheOpenIDConnectfeaturesofAPIGateway,thefollowingarerequired:

l AknowledgeoftheOAuth2.0specification
l AknowledgeofAPIGatewayandPolicyStudio
l AlocalinstallationofAPIGatewayandPolicyStudio
l Adeployedclientdemo(seeUsetheAPIGatewayOAuthclientdemo onpage106)

Oracle API Gateway11.1.2.4.0 OAuth User Guide103


11 API Gateway and OpenID Connect

OpenID Connect flow


TheOpenIDConnectprocessfollowstheOAuth2.0three-leggedauthorizationcodeflow,butwith
theadditionalconceptsofanIDtokenandaUserInfoendpoint.

Theauthorizationcodeflowconsistsofthefollowingsteps:

l Relyingpartypreparesanauthenticationrequestcontainingthedesiredrequestparameters.
l Relyingpartysendstherequesttotheauthorizationserverbyredirectingtheenduserviatheir
useragent(browser).
l Authorizationserverauthenticatestheenduser.
l Authorizationserverobtainsenduserconsentandauthorization.
l Authorizationserversendstheenduserbacktotherelyingpartywithanauthorizationcode.
l Relyingpartyrequestsaresponseusingtheauthorizationcodeatthetokenendpoint.
l ClientreceivesaresponsethatcontainsanIDtokenandaccesstokenintheresponsebody.
l ClientvalidatestheIDtokenandretrievestheenduser'ssubjectidentifier.
Onsuccessfulcompletionofthesestepstheusercanbeconsideredauthenticatedintherelying
party'sapplication.Atthispointtheclientapplicationcanmakearequestforfurtherclaimsand,if
required,createalocalrecordofthisuserforfutureuse,orretrieveapreviouslycreateduserrecord.

Thefollowingdiagramillustratesthesesteps.

Oracle API Gateway11.1.2.4.0 OAuth User Guide104


11 API Gateway and OpenID Connect

Build an OpenID Connect IdP server


TobuildanIdPserverontopofanexistingOAuthdeployment,followthesesteps:

1. AddaCreate ID TokenfiltertothetokenendpointpolicyaftertheAccess Token using


Authorization Codefilter.IfAPIGatewaywillalsosupportimplicitorhybridgranttypesthen
addaCreate ID TokenfiltertotheauthorizationendpointpolicyaftertheAuthorization
Code Flowfilter.
2. CreateaUserInfoendpoint.ThisissimilartoanyOAuthprotectedresourceusingaValidate
Access Tokenfilterwithaminimumscoperequirementofopenid.Afterasuccessful
validationtheUserInfopolicymustcreateaJSONobjectresponserepresentingclaimsaboutthe
userassociatedwiththeaccesstoken.TheusercanbeidentifiedbytheValidate Access
Tokenfilterwiththeauthentication.subject.idmessageproperty.
Thefollowingisanon-normativeexampleoftheJSONresponse:

{
"kind": "APIGatewayOpenIdConnect",
"gender": "femail",
"sub": "sampleuser",
"name": "Sample User",
"given_name": "Sample",
"family_name": "${User}",
"picture": "https://URL.TO.IMAGE/",
"email": "sampleuser@gatweway",
"email_verified": "true",
"locale": "en"
}

Build an OpenID Connect client


BuildingasimpleOpenIDConnectclientinvolvesaddingonlyoneadditionalsteptotheOAuth
authorizationcodeflowforanOAuthclient(seeOAuth2.0exampleclientworkflowonpage85):

1. VerifytheIDtokeninthecallbackpolicyoftheclientapplication.ToverifytheIDtoken,use
theVerify ID Tokenfilter(seeVerifyanOpenIDConnectIDtokenonpage111)aftertheGet
OAuth Access Tokenfilter(seeGetOAuthclientaccesstokenonpage94).IftheVerify ID
TokenfilterreliesonaJSONWebKey(JWK)setforverification,youmustdownload(and
optionallycache)theIdPkeyset.TheclientdemoincludesanexampleofusingtheGoogle
JWKset(seeUsetheAPIGatewayOAuthclientdemo onpage106).
IftheIDtokenissuccessfullyverified,thefilterpassesandthefollowingmessagepropertiesare
created:

l claim(openid.idtoken.claim):TheclaimisaJSONobjectrepresentingbasicclaimsabout
theuser.
l subject(openid.idtoken.sub):ThesubjectistheIdP'suniqueidentifierfortheuser.

Oracle API Gateway11.1.2.4.0 OAuth User Guide105


11 API Gateway and OpenID Connect

Thepolicydesignercandecidehowbesttousetheseproperties.Forexample,thesubjectcouldbe
usedtolookupalocaluserstoretoseeifthereisanexistingrelationshipwiththeuser.Ifthereisno
existinguser,theclaimcouldbeusedtogenerateanewuserrecordforfutureuse.Atthispoint,the
usercanbeconsideredauthenticatedandanewsessioncanbecreated.Ifanaccesstokenwas
returneditcanbeusedtoretrieveadditionalclaimsfromtheIdP'sUserInfoendpoint.

Note WhenAPIGatewayisactingasaclientapplication,theimplicitgranttypeisnotsupported.

Use the API Gateway OAuth client demo


APIGatewayshipswithaclientdemothatshowsatypicalusecaseforOAuth2.0andOpenID
Connect.

Thereareanumberofactorsinvolvedinthisdemo:

l APIGatewayactsasbothaOpenIDConnectrelyingparty(RP)andanOpenIDConnectidentity
provider(IdP).ItalsoactsasabasicOAuthclientapplication,anOAuthauthorizationserver
(AS)andanOAuthresourceserver(RS).
l GoogleisconfiguredasanOAuthASandRSandasanOpenIDConnectIdP
l SalesforceisconfiguredasanOAuthASandRSbutnotasanOpenIDConnectIdP.
TocompletetheconfigurationforGoogleandSalesforceyoumustregisteraclientapplicationwith
eachprovider,andupdatetherelevantproviderprofileswiththereceivedclientIDandsecrets.For
moreinformation,seeAddapplicationcredentialsonpage87.

Whenyouconnecttotheclientdemo(forexample,athttps://localhost:8088),aloginpage
isdisplayed:

Thispagepresentsthreeloginoptions:

1. EnterausernameandpasswordandclickSign In.Whenyousigninwiththisoption,API
Gatewayactsasadirectauthenticationserver.Thisisregularform-basedauthenticationbacked
bytherelevantfilter.Theusercredentialsarecheckedagainstthelocaluserstoreandasession
iscreatedforavaliduser.AfterbeingauthenticatedtheusercaninstantiateanOAuth2.0

Oracle API Gateway11.1.2.4.0 OAuth User Guide106


11 API Gateway and OpenID Connect

authorizationflowtogetanaccesstokenforoneoftheconfiguredOAuthauthentication
servers.
2. Sign in with API Gateway.WhenyousigninwiththisoptionAPIGatewayactsasboththe
RPandthecorrespondingIdP.TheIdProleisconceptuallyaseparateAPIGatewayinstancebut
forthepurposesofthedemoasingleinstancefulfillsbothroles.ThisoptioncausestheAPI
GatewayasRPtoissueanauthorizationredirectthroughtheuseragenttotheIdP.Therequest
includesscopesforanIDtokenandaregularaccesstoken.Afterbeingauthenticatedthe
accesstokencanbeusedtoaccessaprotectedresourceaswellastheUserInfoendpoint.
3. Sign in with Google.WhenyousigninwiththisoptiontheAPIGatewayactsastheRPwith
GoogleactingastheIdP.YoumustupdatetheconfigurationinPolicyStudiotoaddavalidset
ofGoogleOAuthcredentials(seeAddapplicationcredentialsonpage87).Thisoptionredirects
theusertoGoogleforauthenticationandauthorization.Theauthorizationrequestasksfor
OpenIDandaccesstotheuserscalendar.
Note ThecredentialsyoucreatewithGooglemusthaveaccesstotheCalendarand
Google+APIs.

Aftersuccessfulauthentication,youarepresentedwiththefollowingpage:

WhenusingoneofOpenIDConnectoptionstheuserinformationpresentedonthispageisacquired
byaccessingtheUserInfoendpointoftherelevantIdP.TheGet Resourcebuttonusesthereceived
accesstokentoaccessaprotectedresource(forexample,theGoogleresourceaccessedistheuser's
Googlecalendar).

Oracle API Gateway11.1.2.4.0 OAuth User Guide107


11 API Gateway and OpenID Connect

Deploy the client demo


APIGatewayshipswithapreconfiguredclientdemothatdemonstratestheuseofAPIGatewayand
GoogleasOpenIDproviders,andAPIGatewayasaclient.Youmustdeploythedemomanually,as
describedinEnableOAuthmanagementonpage43.

IfyouhavealreadydeployedOAuthusingthedeployOAuthConfig.pyscriptwiththedefault
settings,thedemoisalreadyavailable.IfyouhavedeployedonlytheOAuthserverconfiguration
usingthescript,runthescriptagainwiththe--type=clientdemooptiontodeploytheclient
demo.

Client policies
Themajorityoftheworkinthisdemoiscarriedoutintheclientpolicies.Tosupportthedifferent
methodsofauthentication(form-basedandOpenIDConnect),thedemoisconfiguredtoissuean
anonymoussessiontostarttheprocess.Thisanonymoussessionisreplacedwithanupdateduser
sessionaftertheuserhasbeenidentifiedwitheitherasuccessfulformloginoranIDtoken.

Callback sample
Inthedemoconfigurationthecallbackpolicyfirstchecksifthecurrentsessionisforan
authenticateduser.Ifitisananonymoussessionthepolicyexchangesthecodeforanaccesstoken
andattemptstoverifyanIDtokenifoneisreceived.IftheIDtokenisvaliditsetsthe
authentication.subject.idtothesubidentifierandsavesthetoken.Usingthesubthepolicy
thenchecksthelocaluserstoreforadditionaluserinformation(inthiscasethelocaluserstoreisa
cachesetuptosimulateanactualuserstore).Ifanentrycannotbefoundfortheuser,arequestis
madetotheprovider'sUserInfoendpointusingtheaccesstoken.Asuccessfulrequestupdatesthe
localuserstorewiththereturneduserdata.Finally,anewauthenticatedsessioniscreatedforthe
userandtheyarereturnedtotheclientapplicationhomepagewheretheyarenowsignedin(ina
realworldexampleausermightbepresentedwithaformtoalterorembellishtheretrieveddata
beforeitispersisted).

Oracle API Gateway11.1.2.4.0 OAuth User Guide108


11 API Gateway and OpenID Connect

Oracle API Gateway11.1.2.4.0 OAuth User Guide109


OpenID Connect filters
12
ThissectiondescribesthefiltersyoucanuseforOpenIDConnectflows.Theseinclude:

Filter Description

CreateanOpenIDConnectIDtokenonpage110 CreateanIDtoken.

VerifyanOpenIDConnectIDtokenonpage111 VerifyanIDtoken.

Relatedtopics

l OAuth2.0messageattributesonpage113

Create an OpenID Connect ID token

Overview
YoucanusetheCreate ID TokenfiltertocreateanOpenIDConnectIDtokenwhenAPIGatewayis
actingasanOpenIDConnectserver(alsoknownasOpenIDproviderorOP).Itistheresponsibility
oftheOAuthauthorizationservertogenerateanIDtoken.TheIDtokenisasecuritytokenthat
containsclaimsabouttheauthenticationofanenduserbyanauthorizationserverwhenusinga
client.TheIDtokenisrepresentedasaJSONWebToken(JWT).

TogenerateanIDtokenthefollowingclaimsarerequired:

l iat
l iss
l exp
l sub
l aud

FormoreinformationontherequiredclaimswithinanIDtoken,seetheOpenIDConnect
specification.Thisfilterenablesyoutospecifythesubject(sub),theissuer(iss),andthe
expirationtime(exp)oftheIDtoken.Otherclaims(forexample,iat,exp,andaud)arehandled
internally.TheJWTexpiryinsecondsisappendedontothecurrenttimetogivetheIDtokenan
expiry.

ThisfilteralsoenablesyoutospecifyhowtosigntheIDtoken,andtoaddadditionalclaimstothe
IDtoken.

Oracle API Gateway11.1.2.4.0 OAuth User Guide110


12 OpenID Connect filters

General settings
ConfigurethefollowinggeneralsettingsfortheCreate ID Tokenfilter:
Name:
Enterasuitablenameforthisfilter.

Subject (sub):
Subjectidentifier.Alocallyuniqueandneverreassignedidentifierwithintheissuerfortheend-user,
whichisintendedtobeconsumedbytheclient.Thedefaultvalueis
${authentication.subject.id}.

Issuer (iss):
Issueridentifierfortheissueroftheresponse.Thedefaultvalueis${http.request.url}.

Expiration time in secs (exp):


EntertheexpirytimefortheIDtoken,inseconds.Thedefaultvalueis60seconds.

Apply a signature algorithm:


Selectoneofthefollowingoptions:

l Sign ID token with private key:


SelectthisoptionandclickSigning Keytoselectaprivatekeycertificatethathasbeen
registeredwiththeOpenIDprovider,anduseittosigntheIDtoken.
l Sign using client secret:
SelectthisoptiontosigntheIDtokenusingaclientsecretissuedbytheOpenIDprovider.
Add the following claims:
ClicktheAddbuttontoaddadditionalclaims.YoucanalsoEditorDeleteexistingclaims.

Verify an OpenID Connect ID token

Overview
YoucanusetheVerify ID TokenfiltertoverifyanOpenIDConnectIDtokenusingaJSONWeb
Key(JWK)set,certificate,orclientsecret.TheIDtokenisasecuritytokenthatcontainsclaims
abouttheauthenticationofanenduserbyanauthorizationserverwhenusingaclient.TheIDtoken
isrepresentedasaJSONWebToken(JWT).

Thisfilterrequiresthemessageattributesopenid.idtokenandoauth.client.applicationto
beonthemessagewhiteboard.ThefilterparsestheIDtokenintoaJWTheaderandclaimand
validatesthesignatureusingeitheraJWKset,acertificate,oraclientsecret.Onsuccessthefilter
returnstrueandsetstheIDtoken(openid.idtoken)claimandsubvaluesonthemessage
whiteboard.

FormoreinformationonOpenIDConnect,seetheOpenIDConnectspecification.

Oracle API Gateway11.1.2.4.0 OAuth User Guide111


12 OpenID Connect filters

General settings
ConfigurethefollowinggeneralsettingsfortheVerify ID Tokenfilter:
Name:
Enterasuitablenameforthisfilter.

Clock Skew (seconds):


Enteranumberofsecondstoallowforclockskew.Thisallowsforclockskewwhenverifyingthe
token'sissuedat(iat),expirationtime(exp),andnotbeforevalues.Thedefaultvalueis60
seconds.

Issuer (iss):
Issueridentifierfortheissueroftheresponse.Thedefaultvalueis
${oauth.client.application.getTokenURL().toString()}.

Verify ID Token:
Selectoneofthefollowingoptions:

l With JSON Web Key Set:


SelectthisoptiontoverifytheIDtokenusingaJWKset.
l With Certificate:
SelectthisoptionandclickSigning Keytoselectaprivatekeycertificate,anduseittoverify
theIDtoken.
l With Client Secret:
SelectthisoptiontoverifytheIDtokenusingaclientsecret.

Oracle API Gateway11.1.2.4.0 OAuth User Guide112


Appendix A: OAuth 2.0 message
attributes

ThissectiondescribesthemessageattributesthatareavailableintheAPIGatewayOAuthserverand
OAuthclientfilters.

OAuth 2.0 server message attributes


MostoftheOAuth2.0serverpolicyfiltersintheAPIGatewaygeneratemessageattributesthatcan
bequeriedfurtherusingtheAPIGatewayselectorsyntax.Forexample,themessageattributes
generatedbytheOAuthserverfiltersincludethefollowing:

l accesstoken
l accesstoken.authn
l authzcode
l authentication.subject.id
l oauth.client.details

l scopeattributes
Formoredetailsonselectors,seetheAPIGatewayPolicyDeveloperGuide.

accesstoken methods
Thefollowingmethodsareavailabletocallontheaccesstokenmessageattribute:

${accesstoken.getValue()}
${accesstoken.getExpiration()}
${accesstoken.getExpiresIn()}
${accesstoken.isExpired()}
${accesstoken.getTokenType()}
${accesstoken.getRefreshToken()}
${accesstoken.getOAuth2RefreshToken().getValue()}
${accesstoken.getOAuth2RefreshToken().getExpiration()}
${accesstoken.getOAuth2RefreshToken().getExpiresIn()}
${accesstoken.getOAuth2RefreshToken().hasExpired()}
${accesstoken.hasRefresh()}
${accesstoken.getScope()}
${accesstoken.getAdditionalInformation()}

Thefollowingexampleshowsoutputfromqueryingeachoftheaccesstokenmethods:

Oracle API Gateway11.1.2.4.0 OAuth User Guide113


Appendix A: OAuth 2.0 message attributes

so0HlJYASrnXqn2fL2VWgiunaLfSBhWv6W7JMbmOa131HoQzZB1rNJ
Fri Oct 05 17:16:54 IST 2012
3599
false
Bearer
xif9oNHi83N4ETQLQxmSGoqfu9dKcRcFmBkxTkbc6yHDfK
xif9oNHi83N4ETQLQxmSGoqfu9dKcRcFmBkxTkbc6yHDfK
Sat Oct 06 04:16:54 IST 2012
43199
false
true
https://localhost:8090/auth/userinfo.email
{department=engineering}

accesstoken.authn methods
Thefollowingmethodsareavailabletocallontheaccesstoken.authnmessageattribute:

${accesstoken.authn.getUserAuthentication()}
${accesstoken.authn.getAuthorizationRequest().getScope()}
${accesstoken.authn.getAuthorizationRequest().getClientId()}
${accesstoken.authn.getAuthorizationRequest().getState()}
${accesstoken.authn.getAuthorizationRequest().getRedirectUri()}
${accesstoken.authn.getAuthorizationRequest().getParameters()}

Thefollowingexampleshowsoutputfromqueryingeachoftheaccesstoken.authnmethods:

admin
[https://localhost:8090/auth/userinfo.email]
SampleConfidentialApp
343dqak32ksla
https://localhost/oauth_callback
{client_secret=6808d4b6-ef09-4b0d-8f28-3b05da9c48ec,
scope=https://localhost:8090/auth/userinfo.email, grant_type=authorization_code,
redirect_uri=https://localhost/oauth_callback, state=null,
code=FOT4nudbglQouujRl8oH3EOMzaOlQP, client_id=SampleConfidentialApp}

authzcode methods
Thefollowingmethodsareavailabletocallontheauthzcodemessageattribute:

${authzcode.getCode()}
${authzcode.getState()}
${authzcode.getApplicationName()}
${authzcode.getExpiration()}

Oracle API Gateway11.1.2.4.0 OAuth User Guide114


Appendix A: OAuth 2.0 message attributes

${authzcode.getExpiresIn()}
${authzcode.getRedirectURI()}
${authzcode.getScopes()}
${authzcode.getUserIdentity()}
${authzcode.getAdditionalInformation()}

Thefollowingexampleshowsoutputfromqueryingeachoftheauthzcodemethods:

F8aHby7zctNRknmWlp3voe61H20Md1
sds12dsd3343ddsd
SampleConfidentialApp
Fri Oct 05 15:47:39 IST 2012
599 (expiry in secs)
https://localhost/oauth_callback
[https://localhost:8090/auth/userinfo.email]
admin
{costunit=hr}

oauth.client.details methods
Thefollowingmethodsareavailabletocallontheoauth.client.detailsmessageattribute:

${oauth.client.details.getClientType()}
${oauth.client.details.getApplication()}
${oauth.client.details.getBase64EncodedCert()}
${oauth.client.details.getX509Cert()}
${oauth.client.details.getName()}
${oauth.client.details.getDescription()}
${oauth.client.details.getLogo()}
${oauth.client.details.getApplicationID()}
${oauth.client.details.getContactPhone()}
${oauth.client.details.getContactEmail()}
${oauth.client.details.getClientID()}
${oauth.client.details.getClientSecret()}
${oauth.client.details.getRedirectURLs()}
${oauth.client.details.getScopes()}
${oauth.client.details.getDefaultScopes()}
${oauth.client.details.isEnabled()}

Thefollowingexampleshowsoutputfromqueryingeachoftheoauth.client.details
methods:

confidential
com.vordel.common.apiserver.model.Application@126c334d
-----BEGIN CERTIFICATE-----MIICwzCCAasCBgE6HBsdpzANBg ......END CERTIFICATE
CN=Change this for production

Oracle API Gateway11.1.2.4.0 OAuth User Guide115


Appendix A: OAuth 2.0 message attributes

Demo App
Demo App Desc
https://localhost:80/images/logo.png
dce2efc8-e9d4-4976-8a0f-3d2a2ec3a26d
000-111-222-333
temp@axway.com
d0e8952f-cefe-18e1-b2bf-8accdc456933
796501dd-7df5-4a94-a111-146c7bbab22a
[https://localhost:8088/redirect]
[com.vordel.common.apiserver.discovery.model.OAuthAppScope@6a25ce50]
[com.vordel.common.apiserver.discovery.model.OAuthAppScope@6a25ce50,
com.vordel.common.apiserver.discovery.model.OAuthAppScope@580c1ca1]
true

Example of querying a message attribute


IfyouaddadditionalaccesstokenparameterstotheOAuthAccess Token Infofilter,youcan
returnalotofadditionalinformationaboutthetoken.Forexample:

{
"audience" :"SampleConfidentialApp",
"user_id" :"admin",
"scope" :"https://localhost:8090/auth/userinfo.email",
"expires_in" :3567,
"Access Token Expiry Date" :"Wed Aug 15 11:19:19 IST 2012",
"Authentication parameters" :"{username=admin,
client_secret=6808d4b6-ef09-4b0d-8f28-3b05da9c48ec,
scope=https://localhost:8090/auth/userinfo.email, grant_type=password,
redirect_uri=null, state=null, client_id=SampleConfidentialApp,
password=xxxxxxxx}",
"Access Token Type:" :"Bearer"

Oracle API Gateway11.1.2.4.0 OAuth User Guide116


Appendix A: OAuth 2.0 message attributes

Youalsohavetheaddedflexibilitytoaddextraname/valuepairsettingstoaccesstokensupon
generation.TheOAuth2.0accesstokengenerationfiltersprovideanoptiontostoreadditional
parametersforanaccesstoken.Forexample,ifyouaddthename/valuepair
Department/EngineeringtotheClient Credentialsfilter:

YoucanthenupdatetheAccess Token Infofiltertoaddaname/valuepairusingaselectortoget


thefollowingvalue:

Department/${accesstoken.getAdditionalInformation().get("Department")}

Oracle API Gateway11.1.2.4.0 OAuth User Guide117


Appendix A: OAuth 2.0 message attributes

Forexample:

ThentheJSONresponseisasfollows:

{
"audience" :"SampleConfidentialApp",
"user_id" :"SampleConfidentialApp",
"scope" :"https://localhost:8090/auth/userinfo.email",
"expires_in" :3583,
"Access Token Type:" :"Bearer",
"Authentication parameters" :"{client_secret=6808d4b6-ef09-4b0d-8f28-3b05da9c48ec,
scope=https://localhost:8090/auth/userinfo.email, grant_type=client_credentials,
redirect_uri=null, state=null, client_id=SampleConfidentialApp}",
"Department" :"Engineering",
"Access Token Expiry Date" :"Wed Aug 15 12:10:57 IST 2012"

YoucanalsouseAPIGatewayselectorsyntaxwhenstoringadditionalinformationwiththetoken.
Formoredetailsonselectors,seetheAPIGatewayPolicyDeveloperGuide.

OAuth scope attributes


Inaddition,thefollowingmessageattributesareusedbytheOAuthfilterstomanageOAuthscopes.
Thescopesarestoredasasetofstrings(forexample,resource.READandresource.WRITE):

l scopes.in.token

StorestheOAuthscopesthathavebeensentintotheauthorizationserverwhenrequestingthe
accesstoken.
l scopes.for.token

StorestheOAuthscopesthathavebeengrantedfortheaccesstokenrequest.
l scopes.required

Oracle API Gateway11.1.2.4.0 OAuth User Guide118


Appendix A: OAuth 2.0 message attributes

UsedbytheValidate Access Tokenfilteronly.IfthereisafailureaccessinganOAuthresource


duetoincorrectscopesintheaccesstoken,aninsufficent_scopeexceptionissentbackin
theWWW-Authenticateheader.WhenGet scopes by calling a policyisset,theconfigured
policycansetthescopes.requiredmessageattribute.ThisenablestheOAuthresourceserver
toproperlyinteractwithclientapplicationsandprovideusefulerrorresponsemessages.For
example:

WWW-Authenticate Bearer realm="DefaultRealm",


error="insufficient_scope",
error_description="scope(s) associated with access token are not valid to access
this resource",
scope="Scopes must match All of these scopes:https://localhost:8090/auth/user.photos
https://localhost:8090/auth/userinfo.email"

OAuth SAML bearer attributes


Themessageattributeoauth.saml.docissetonthemessagewhiteboardbytheAccess Token
using SAML Assertionfilter.ThisisaW3CDOMdocumentviewoftheSAMLbearerassertionthat
APIGatewayreceivesfromanOAuthclientapplication.Thedocumentinthisformcanbeverifiedby
otherfilters,butinanOAuthcontexttheXML Signature Verificationistypicallyused.Formore
information,seetheXML Signature VerificationfilterintheAPIGatewayPolicyDeveloper
Guide.

OAuth 2.0 client message attributes


TheOAuth2.0clientpolicyfiltersinAPIGatewaygeneratemessageattributesthatcanbequeried
furtherusingtheAPIGatewayselectorsyntax.ThemessageattributesgeneratedbytheOAuth2.0
clientfiltersincludethefollowing:

l oauth.client.accesstoken
l oauth.client.application

Formoredetailsonselectors,seetheAPIGatewayPolicyDeveloperGuide.

oauth.client.accesstoken methods
Thefollowingmethodsareavailabletocallontheoauth.client.accesstokenmessage
attribute:

${oauth.client.accesstoken.getAuthentication()}
${oauth.client.accesstoken.getClientId()}
${oauth.client.accesstoken.getAccessToken()}
${oauth.client.accesstoken.getCreated()}

Oracle API Gateway11.1.2.4.0 OAuth User Guide119


Appendix A: OAuth 2.0 message attributes

${oauth.client.accesstoken.isExpired()}
${oauth.client.accesstoken.hasRefresh()}
${oauth.client.accesstoken.getRefreshToken()}
${oauth.client.accesstoken.getExpiresIn()}
${oauth.client.accesstoken.getExpiryDate()}
${oauth.client.accesstoken.getParams()}
${oauth.client.accesstoken.getTokenType()}

Thefollowingexampleshowsoutputfromqueryingeachoftheoauth.client.accesstoken
methods:

regadmin
ClientConfidentialApp
SIDnxbYabJwRZpKexUx6R3dTEwKOj0afQo7sr2DrDYuJaVCAb9xvPBk
Thu Mar 06 12:34:44 GMT 2014
false
true
GokdAuu706ydZtNkl92UEPmnJRNmVBJPiPVGGrEwXKz5Uh
3599
Thu Mar 06 13:34:43 GMT 2014
{state=9a388d14-a0e9-4b32-9003-e322c93279dd, scope=resource.WRITE}

oauth.client.application methods
Thisattributerepresentstheproviderprofileselectedinthefilter.Itcontainstheproviderdetails,
suchastokenandauthorizationendpoints,andthetokenstore,aswellasthespecificsoftheclient
applicationincludingtheclientIDandsecret.Thefollowingmethodsareavailabletocallonthe
oauth.client.applicationmessageattribute:

${oauth.client.application.getTokenURL()}
${oauth.client.application.getAuthentication()}
${oauth.client.application.getProviderName()}
${oauth.client.application.getAppName()}
${oauth.client.application.getClientID()}
${oauth.client.application.getFlow()}
${oauth.client.application.getClientSecret()}
${oauth.client.application.getExtraTokenRequestProps()}
${oauth.client.application.getScopes()}
${oauth.client.application.getLocationOfClientDetails()}
${oauth.client.application.getClientIdHeaderName()}
${oauth.client.application.getClientSecretHeaderName()}
${oauth.client.application.getTokenStore()}
${oauth.client.application.getToken()}
${oauth.client.application.getTokenFromStore()}
${oauth.client.application.getProvider()}

Oracle API Gateway11.1.2.4.0 OAuth User Guide120


Appendix A: OAuth 2.0 message attributes

Thefollowingexampleshowsoutputfromqueryingeachoftheoauth.client.application
methods:

https://127.0.0.1:8089/api/oauth/token
regadmin
API Gateway
Sample Client Authzcode App
ClientConfidentialApp
authorization_code
9cb76d80-1bc2-48d3-8d31-edeec0fddf6c
{}
[resource.WRITE]
QueryString
client_id
client_secret
an object of type com.vordel.circuit.oauth.persistence.SynchronizedClientTokenStore
an object of type com.vordel.oauth.client.store.OAuth2ClientAccessToken
an object of type com.vordel.oauth.client.store.OAuth2ClientAccessToken
an object of type com.vordel.oauth.client.providers.BaseOAuth2Provider

Oracle API Gateway11.1.2.4.0 OAuth User Guide121

Anda mungkin juga menyukai