OpenID Connect | Google Identity
文章推薦指數: 80 %
The implicit flow is used when a client-side application (typically a JavaScript app running in the browser) needs to access APIs directly ... Google Identity Overview OAuth2.0 Overview Cross-clientIdentity OAuth2.0ScopesforGoogleAPIs OAuth2.0Policies OpenIDConnect Cross-AccountProtection(RISC) SignInWithGoogle Android OneTap GoogleSign-In PhoneNumberHint iOSandmacOS GoogleSign-In Web SignInWithGoogle GoogleSign-In(Legacy) CaseStudies CaseStudies AccountLinking BlockStore Overview Testing SmartLock SmartLockforAndroid SmartLockforChrome FIDOauthentication FastIDentityOnlineauthentication FIDOauthentication FIDO2forAndroid Language English BahasaIndonesia Deutsch Español Español–AméricaLatina Français Italiano Polski Português–Brasil TiếngViệt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文–简体 中文–繁體 日本語 한국어 Signin UsingOAuth2.0toAccessGoogleAPIs Google Identity Overview OAuth2.0 More SignInWithGoogle More AccountLinking BlockStore More SmartLock More FIDOauthentication More Overview Cross-clientIdentity OAuth2.0Scopes OAuth2.0Policies AccesstoGoogleAPIs forServer-sideWebApps forJavaScriptWebApps forMobile&DesktopApps forTV&DeviceApps forServiceAccounts Prepareyourappforproduction ComplywithOAuth2.0policies Submitforbrandverification Relatedtopics OpenIDConnect Cross-AccountProtection(RISC) Overview Cross-clientIdentity OAuth2.0ScopesforGoogleAPIs OAuth2.0Policies OpenIDConnect Cross-AccountProtection(RISC) Android OneTap GoogleSign-In PhoneNumberHint iOSandmacOS GoogleSign-In Web SignInWithGoogle GoogleSign-In(Legacy) CaseStudies CaseStudies Overview Testing SmartLockforAndroid SmartLockforChrome FastIDentityOnlineauthentication FIDOauthentication FIDO2forAndroid Home Products GoogleIdentity OAuth2.0 Sendfeedback OpenIDConnect Google'sOAuth2.0APIscanbeusedforbothauthenticationandauthorization.Thisdocument describesourOAuth2.0implementationforauthentication,whichconformstothe OpenIDConnectspecification,andis OpenIDCertified.The documentationfoundinUsingOAuth2.0toAccessGoogle APIsalsoappliestothisservice.Ifyouwanttoexplorethisprotocolinteractively,we recommendthe GoogleOAuth2.0Playground. Togethelpon StackOverflow, tagyourquestionswith'google-oauth'. Note:Ifyouwanttoprovidea"Sign-inwithGoogle"buttonforyourwebsiteorapp, werecommendusingGoogleSign-In,oursign-inclient librarythatisbuiltontheOpenIDConnectprotocolandprovidesOpenIDConnectformatted IDTokens. SettingupOAuth2.0 BeforeyourapplicationcanuseGoogle'sOAuth2.0authenticationsystemforuserlogin,you mustsetupaprojectintheGoogleAPIConsoletoobtainOAuth2.0 credentials,setaredirectURI,and(optionally)customizethebrandinginformationthatyour usersseeontheuser-consentscreen.Youcanalsousethe APIConsoletocreateaserviceaccount,enablebilling,set upfiltering,anddoothertasks.Formoredetails,seethe GoogleAPIConsole Help. ObtainOAuth2.0credentials YouneedOAuth2.0credentials,includingaclientIDandclientsecret,toauthenticateusers andgainaccesstoGoogle'sAPIs. ToviewtheclientIDandclientsecretforagivenOAuth2.0credential,clickthefollowing text:Select credential.Inthewindowthatopens,chooseyourprojectandthecredentialyouwant,then clickView. Or,viewyourclientIDandclientsecretfromtheCredentialspagein APIConsole: GototheCredentialspage. Clickthenameofyourcredentialorthepencil(create)icon. YourclientIDandsecretareatthetopofthepage. SetaredirectURI TheredirectURIthatyousetintheAPIConsoledetermines whereGooglesendsresponsestoyourauthenticationrequests. Tocreate,view,oredittheredirectURIsforagivenOAuth2.0credential,dothe following: GototheCredentialspage. IntheOAuth2.0clientIDssectionofthepage,clickacredential. VieworedittheredirectURIs. IfthereisnoOAuth2.0clientIDssectionontheCredentialspage,thenyourprojecthas noOAuthcredentials.Tocreateone,clickCreatecredentials. Customizetheuserconsentscreen Foryourusers,theOAuth2.0authenticationexperienceincludesaconsentscreenthat describestheinformationthattheuserisreleasingandthetermsthatapply.Forexample,when theuserlogsin,theymightbeaskedtogiveyourappaccesstotheiremailaddressandbasic accountinformation.Yourequestaccesstothisinformationusingthe scopeparameter,whichyourappincludesinits authenticationrequest.Youcanalsousescopestorequestaccess tootherGoogleAPIs. Theuserconsentscreenalsopresentsbrandinginformationsuchasyourproductname,logo,and ahomepageURL.Youcontrolthebrandinginformationinthe APIConsole. Toenableyourproject'sconsentscreen: OpentheConsentScreenpageinthe GoogleAPIConsole. Ifprompted,selectaproject,orcreateanewone. FillouttheformandclickSave. ThefollowingconsentdialogshowswhatauserwouldseewhenacombinationofOAuth2.0and GoogleDrivescopesarepresentintherequest.(Thisgenericdialogwasgeneratedusing theGoogleOAuth2.0Playground, soitdoesnotincludebrandinginformationthatwouldbesetinthe APIConsole.) Accessingtheservice Googleandthirdpartiesprovidelibrariesthatyoucanusetotakecareofmanyofthe implementationdetailsofauthenticatingusersandgainingaccesstoGoogleAPIs.Examples includeGoogleSign-Inandthe Googleclientlibraries,whichareavailableforavarietyof platforms. Note:Giventhesecurityimplicationsofgettingtheimplementation correct,westronglyencourageyoutotakeadvantageofapre-writtenlibraryor service. Authenticatingusersproperlyisimportanttotheirandyoursafetyandsecurity,andusing well-debuggedcodewrittenbyothersisgenerallyabestpractice.Formoreinformation,see Clientlibraries. Ifyouchoosenottousealibrary,followtheinstructionsintheremainderofthisdocument, whichdescribestheHTTPrequestflowsthatunderlytheavailablelibraries. Authenticatingtheuser AuthenticatingtheuserinvolvesobtaininganIDtokenandvalidatingit. IDtokens areastandardizedfeatureof OpenIDConnectdesignedforusein sharingidentityassertionsontheInternet. ThemostcommonlyusedapproachesforauthenticatingauserandobtaininganIDtokenare calledthe"server"flowandthe"implicit"flow.Theserverflowallowstheback-endserverof anapplicationtoverifytheidentityofthepersonusingabrowserormobiledevice.The implicitflowisusedwhenaclient-sideapplication(typicallyaJavaScriptapprunninginthe browser)needstoaccessAPIsdirectlyinsteadofviaitsback-endserver. Thisdocumentdescribeshowtoperformtheserverflowforauthenticatingtheuser.The implicitflowissignificantlymorecomplicatedbecauseofsecurityrisksinhandlingandusing tokensontheclientside.Ifyouneedtoimplementanimplicitflow,wehighlyrecommendusing GoogleSign-In. Serverflow Makesureyousetupyourappinthe APIConsoletoenableittousetheseprotocolsand authenticateyourusers.WhenausertriestologinwithGoogle,youneedto: Createananti-forgerystatetoken SendanauthenticationrequesttoGoogle Confirmtheanti-forgerystatetoken ExchangecodeforaccesstokenandIDtoken ObtainuserinformationfromtheIDtoken Authenticatetheuser 1.Createananti-forgerystatetoken Youmustprotectthesecurityofyourusersbypreventingrequestforgeryattacks.Thefirst stepiscreatingauniquesessiontokenthatholdsstatebetweenyourappandtheuser'sclient. Youlatermatchthisuniquesessiontokenwiththeauthenticationresponsereturnedbythe GoogleOAuthLoginservicetoverifythattheuserismakingtherequestandnotamalicious attacker.Thesetokensareoftenreferredtoascross-siterequestforgery (CSRF) tokens. Onegoodchoiceforastatetokenisastringof30orsocharactersconstructedusinga high-qualityrandom-numbergenerator.Anotherisahashgeneratedbysigningsomeofyour sessionstatevariableswithakeythatiskeptsecretonyourback-end. Thefollowingcodedemonstratesgeneratinguniquesessiontokens. PHP Youmustdownloadthe GoogleAPIsclientlibraryforPHP tousethissample. //Createastatetokentopreventrequestforgery. //Storeitinthesessionforlatervalidation. $state=bin2hex(random_bytes(128/8)); $app['session']->set('state',$state); //SettheclientID,tokenstate,andapplicationnameintheHTMLwhile //servingit. return$app['twig']->render('index.html',array( 'CLIENT_ID'=>CLIENT_ID, 'STATE'=>$state, 'APPLICATION_NAME'=>APPLICATION_NAME )); Java Youmustdownloadthe GoogleAPIsclientlibraryforJava tousethissample. //Createastatetokentopreventrequestforgery. //Storeitinthesessionforlatervalidation. Stringstate=newBigInteger(130,newSecureRandom()).toString(32); request.session().attribute("state",state); //Readindex.htmlintomemory,andsettheclientID, //tokenstate,andapplicationnameintheHTMLbeforeservingit. returnnewScanner(newFile("index.html"),"UTF-8") .useDelimiter("\\A").next() .replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}",CLIENT_ID) .replaceAll("[{]{2}\\s*STATE\\s*[}]{2}",state) .replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APPLICATION_NAME); Python Youmustdownloadthe GoogleAPIsclientlibraryforPython tousethissample. #Createastatetokentopreventrequestforgery. #Storeitinthesessionforlatervalidation. state=hashlib.sha256(os.urandom(1024)).hexdigest() session['state']=state #SettheclientID,tokenstate,andapplicationnameintheHTMLwhile #servingit. response=make_response( render_template('index.html', CLIENT_ID=CLIENT_ID, STATE=state, APPLICATION_NAME=APPLICATION_NAME)) 2.SendanauthenticationrequesttoGoogle ThenextstepisforminganHTTPSGETrequestwiththeappropriateURIparameters. NotetheuseofHTTPSratherthanHTTPinallthestepsofthisprocess;HTTPconnectionsare refused.YoushouldretrievethebaseURIfromtheDiscoverydocument usingtheauthorization_endpointmetadatavalue.Thefollowingdiscussionassumes thebaseURIishttps://accounts.google.com/o/oauth2/v2/auth. Forabasicrequest,specifythefollowingparameters: client_id,whichyouobtainfromthe APIConsole Credentialspage . response_type,whichinabasicauthorizationcodeflowrequestshouldbe code.(Readmoreat response_type.) scope,whichinabasicrequestshouldbeopenidemail. (Readmoreatscope.) redirect_urishouldbetheHTTPendpointonyourserverthatwillreceivethe responsefromGoogle.ThevaluemustexactlymatchoneoftheauthorizedredirectURIsforthe OAuth2.0client,whichyouconfiguredintheAPIConsole Credentialspage.Ifthisvaluedoesn'tmatchanauthorized URI,therequestwillfailwitharedirect_uri_mismatcherror. stateshouldincludethevalueoftheanti-forgeryuniquesessiontoken,as wellasanyotherinformationneededtorecoverthecontextwhentheuserreturnstoyour application,e.g.,thestartingURL. (Readmoreatstate.) nonceisarandomvaluegeneratedbyyourappthatenablesreplayprotection whenpresent. login_hintcanbetheuser'semailaddressorthesubstring, whichisequivalenttotheuser'sGoogleID.Ifyoudonotprovidealogin_hint andtheuseriscurrentlyloggedin,theconsentscreenincludesarequestforapprovalto releasetheuser'semailaddresstoyourapp. (Readmoreatlogin_hint.) UsethehdparametertooptimizetheOpenIDConnectflowforusersofa particulardomainassociatedwithaGoogleCloudorganization.(Readmoreat hd.) Note:Onlythemostcommonlyusedparametersarelistedabove.Fora completelist,plusmoredetailsaboutalltheparameters,see AuthenticationURIparameters. HereisanexampleofacompleteOpenIDConnectauthenticationURI,withlinebreaksandspaces forreadability: https://accounts.google.com/o/oauth2/v2/auth? response_type=code& client_id=424911365001.apps.googleusercontent.com& scope=openid%20email& redirect_uri=https%3A//oauth2.example.com/code& state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foauth2-login-demo.example.com%2FmyHome& [email protected]& nonce=0394852-3190485-2490358& hd=example.com Usersarerequiredtogiveconsentifyourapprequestsanynewinformationaboutthem,orif yourapprequestsaccountaccessthattheyhavenotpreviouslyapproved. 3.Confirmanti-forgerystatetoken Theresponseissenttotheredirect_urithatyouspecifiedinthe request.Allresponsesarereturnedinthequerystring,asshown below: https://oauth2.example.com/code?state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foa2cb.example.com%2FmyHome&code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&scope=openid%20email%20https://www.googleapis.com/auth/userinfo.email Ontheserver,youmustconfirmthatthestatereceivedfromGooglematchesthe sessiontokenyoucreatedinStep1.Thisround-tripverification helpstoensurethattheuser,notamaliciousscript,ismakingtherequest. ThefollowingcodedemonstratesconfirmingthesessiontokensthatyoucreatedinStep1: PHP Youmustdownloadthe GoogleAPIsclientlibraryforPHP tousethissample. //Ensurethatthereisnorequestforgerygoingon,andthattheuser //sendingusthisconnectrequestistheuserthatwassupposedto. if($request->get('state')!=($app['session']->get('state'))){ returnnewResponse('Invalidstateparameter',401); } Java Youmustdownloadthe GoogleAPIsclientlibraryforJava tousethissample. //Ensurethatthereisnorequestforgerygoingon,andthattheuser //sendingusthisconnectrequestistheuserthatwassupposedto. if(!request.queryParams("state").equals( request.session().attribute("state"))){ response.status(401); returnGSON.toJson("Invalidstateparameter."); } Python Youmustdownloadthe GoogleAPIsclientlibraryforPython tousethissample. #Ensurethattherequestisnotaforgeryandthattheusersending #thisconnectrequestistheexpecteduser. ifrequest.args.get('state','')!=session['state']: response=make_response(json.dumps('Invalidstateparameter.'),401) response.headers['Content-Type']='application/json' returnresponse 4.ExchangecodeforaccesstokenandIDtoken Theresponseincludesacodeparameter,aone-timeauthorizationcodethatyour servercanexchangeforanaccesstokenandIDtoken.Yourservermakesthisexchangebysending anHTTPSPOSTrequest.ThePOSTrequestissenttothetokenendpoint, whichyoushouldretrievefromtheDiscoverydocumentusingthe token_endpointmetadatavalue.Thefollowingdiscussionassumestheendpointis https://oauth2.googleapis.com/token.Therequestmustincludethefollowingparametersin thePOSTbody: Fields code Theauthorizationcodethatisreturnedfrom theinitialrequest. client_id TheclientIDthatyouobtainfromtheAPIConsole Credentialspage,asdescribedin ObtainOAuth2.0credentials. client_secret TheclientsecretthatyouobtainfromtheAPIConsole Credentialspage,asdescribedin ObtainOAuth2.0credentials. redirect_uri AnauthorizedredirectURIforthegivenclient_idspecifiedinthe APIConsole Credentialspage,asdescribedin SetaredirectURI. grant_type Thisfieldmustcontainavalueofauthorization_code, asdefinedintheOAuth2.0specification. Theactualrequestmightlooklikethefollowingexample: POST/tokenHTTP/1.1 Host:oauth2.googleapis.com Content-Type:application/x-www-form-urlencoded code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& client_id=your-client-id& client_secret=your-client-secret& redirect_uri=https%3A//oauth2.example.com/code& grant_type=authorization_code AsuccessfulresponsetothisrequestcontainsthefollowingfieldsinaJSONarray: Fields access_token AtokenthatcanbesenttoaGoogleAPI. expires_in Theremaininglifetimeoftheaccesstokeninseconds. id_token AJWTthatcontains identityinformationabouttheuserthatisdigitallysignedbyGoogle. scope Thescopesofaccessgrantedbytheaccess_tokenexpressedasalistof space-delimited,case-sensitivestrings. token_type Identifiesthetypeoftokenreturned.Atthistime,thisfieldalwayshasthevalue Bearer. refresh_token (optional) Thisfieldisonlypresentifthe access_typeparameterwassetto offlineintheauthenticationrequest. Fordetails,seeRefreshtokens. Note:ThereisalimittothenumberoftokensperGoogleuseraccount, andanyauthenticationrequestabovethislimitmightquietlyinvalidateanoutstandingrefresh token.Fordetails,see Tokenexpiration. 5.ObtainuserinformationfromtheIDtoken AnIDTokenisaJWT (JSONWebToken),thatis,acryptographicallysignedBase64-encodedJSONobject.Normally,it iscriticalthatyouvalidateanIDtokenbeforeyouuseit, butsinceyouarecommunicatingdirectlywithGoogleoveranintermediary-freeHTTPSchanneland usingyourclientsecrettoauthenticateyourselftoGoogle,youcanbeconfidentthatthetoken youreceivereallycomesfromGoogleandisvalid.IfyourserverpassestheIDtokentoother componentsofyourapp,itisextremelyimportantthattheothercomponents validatethetokenbeforeusingit. SincemostAPIlibrariescombinethevalidationwiththeworkofdecodingthebase64url-encoded valuesandparsingtheJSONwithin,youwillprobablyendupvalidatingthetokenanywayasyou accesstheclaimsintheIDtoken. AnIDtoken'spayload AnIDtokenisaJSONobjectcontainingasetofname/valuepairs.Here'sanexample,formatted forreadability: { "iss":"https://accounts.google.com", "azp":"1234987819200.apps.googleusercontent.com", "aud":"1234987819200.apps.googleusercontent.com", "sub":"10769150350006150715113082367", "at_hash":"HK6E_P6Dh8Y93mRNtsDB1Q", "hd":"example.com", "email":"[email protected]", "email_verified":"true", "iat":1353601026, "exp":1353604926, "nonce":"0394852-3190485-2490358" } GoogleIDTokensmaycontainthefollowingfields(knownasclaims): Claim Provided Description aud always TheaudiencethatthisIDtokenisintendedfor.ItmustbeoneoftheOAuth2.0client IDsofyourapplication. exp always ExpirationtimeonorafterwhichtheIDtokenmustnotbeaccepted.Representedin Unixtime(integerseconds). iat always ThetimetheIDtokenwasissued.RepresentedinUnixtime(integerseconds). iss always TheIssuerIdentifierfortheIssueroftheresponse.Always https://accounts.google.comoraccounts.google.comforGoogle IDtokens. sub always Anidentifierfortheuser,uniqueamongallGoogleaccountsandneverreused.AGoogle accountcanhavemultipleemailaddressesatdifferentpointsintime,butthe subvalueisneverchanged.Usesubwithinyourapplication astheunique-identifierkeyfortheuser.Maximumlengthof255case-sensitiveASCII characters. at_hash Accesstokenhash.Providesvalidationthattheaccesstokenistiedtotheidentity token.IftheIDtokenisissuedwithanaccess_tokenvalueintheserver flow,thisclaimisalwaysincluded.Thisclaimcanbeusedasanalternatemechanismto protectagainstcross-siterequestforgeryattacks,butifyoufollow Step1andStep3itisnot necessarytoverifytheaccesstoken. azp Theclient_idoftheauthorizedpresenter.Thisclaimisonlyneededwhen thepartyrequestingtheIDtokenisnotthesameastheaudienceoftheIDtoken.This maybethecaseatGoogleforhybridappswhereawebapplicationandAndroidapphavea differentOAuth2.0client_idbutsharethesameGoogleAPIsproject. email Theuser'semailaddress.Thisvaluemaynotbeuniquetothisuserandisnotsuitable foruseasaprimarykey.Providedonlyifyourscopeincludedtheemail scopevalue. email_verified Trueiftheuser'se-mailaddresshasbeenverified;otherwisefalse. family_name Theuser'ssurname(s)orlastname(s).Mightbeprovidedwhena nameclaimispresent. given_name Theuser'sgivenname(s)orfirstname(s).Mightbeprovidedwhena nameclaimispresent. hd ThedomainassociatedwiththeGoogleCloudorganizationoftheuser.Providedonlyif theuserbelongstoaGoogleCloudorganization. locale Theuser'slocale,representedbya BCP47languagetag. Mightbeprovidedwhenanameclaimis present. name Theuser'sfullname,inadisplayableform.Mightbeprovidedwhen: Therequestscopeincludedthestring"profile" TheIDtokenisreturnedfromatokenrefresh Whennameclaimsarepresent,youcanusethemtoupdateyourapp'suser records.Notethatthisclaimisneverguaranteedtobepresent. nonce Thevalueofthenoncesuppliedbyyourappintheauthenticationrequest. Youshouldenforceprotectionagainstreplayattacksbyensuringitispresentedonly once. picture TheURLoftheuser'sprofilepicture.Mightbeprovidedwhen: Therequestscopeincludedthestring"profile" TheIDtokenisreturnedfromatokenrefresh Whenpictureclaimsarepresent,youcanusethemtoupdateyourapp's userrecords.Notethatthisclaimisneverguaranteedtobepresent. profile TheURLoftheuser'sprofilepage.Mightbeprovidedwhen: Therequestscopeincludedthestring"profile" TheIDtokenisreturnedfromatokenrefresh Whenprofileclaimsarepresent,youcanusethemtoupdateyourapp's userrecords.Notethatthisclaimisneverguaranteedtobepresent. 6.Authenticatetheuser AfterobtaininguserinformationfromtheIDtoken,youshouldqueryyourapp'suserdatabase. Iftheuseralreadyexistsinyourdatabase,youshouldstartanapplicationsessionforthat userifallloginrequirementsaremetbytheGoogleAPIresponse. Iftheuserdoesnotexistinyouruserdatabase,youshouldredirecttheusertoyournew-user sign-upflow.Youmaybeabletoauto-registertheuserbasedontheinformationyoureceive fromGoogle,orattheveryleastyoumaybeabletopre-populatemanyofthefieldsthatyou requireonyourregistrationform.InadditiontotheinformationintheIDtoken,youcanget additionaluserprofileinformationatouruser profileendpoints. Advancedtopics ThefollowingsectionsdescribetheGoogleOAuth2.0APIingreaterdetail.Thisinformationis intendedfordeveloperswithadvancedrequirementsaroundauthenticationandauthorization. AccesstootherGoogleAPIs OneoftheadvantagesofusingOAuth2.0forauthenticationisthatyourapplicationcanget permissiontouseotherGoogleAPIsonbehalfoftheuser(suchasYouTube,GoogleDrive, Calendar,orContacts)atthesametimeasyouauthenticatetheuser.Todothis,includethe otherscopesthatyouneedintheauthenticationrequestthatyou sendtoGoogle.Forexample,toadduser'sagegrouptoyourauthenticationrequest,passa scopeparameterof openidemailhttps://www.googleapis.com/auth/profile.agerange.read.Theuseris promptedappropriatelyontheconsentscreen.Theaccess tokenthatyoureceivebackfromGoogleallowsyoutoaccessalltheAPIsrelatedtothescopes ofaccessyourequestedandweregranted. Note:Ifyourapplicationisaskingformanyscopes,theconsentscreen containsmanylinesoftext.Themorescopesyourapplicationrequests,thelesslikelyitis thattheuserwillconsent,soyourapplicationshouldaskonlyforthescopesitneeds. Refreshtokens InyourrequestforAPIaccessyoucanrequestarefreshtokentobereturnedduringthe codeexchange.Arefreshtokenprovidesyourapp continuousaccesstoGoogleAPIswhiletheuserisnotpresentinyourapplication.Torequesta refreshtoken,addsetthe access_typeparametertoofflinein yourauthenticationrequest. Considerations: Besuretostoretherefreshtokensafelyandpermanently,becauseyoucanonlyobtaina refreshtokenthefirsttimethatyouperformthecodeexchangeflow. Therearelimitsonthenumberofrefreshtokensthatareissued:onelimitperclient/user combination,andanotherperuseracrossallclients.Ifyourapplicationrequeststoomany refreshtokens,itmayrunintotheselimits,inwhichcaseolderrefreshtokensstop working. Formoreinformation,see Refreshinganaccesstoken (offlineaccess). Promptingre-consent Youcanprompttheusertore-authorizeyourappbysettingthe promptparametertoconsentinyour authenticationrequest.Whenprompt=consentis included,theconsentscreenisdisplayedeverytimeyourapprequestsauthorizationofscopes ofaccess,evenifallscopeswerepreviouslygrantedtoyourGoogleAPIsproject.Forthis reason,includeprompt=consentonlywhennecessary. Formoreaboutthepromptparameter,seeprompt intheAuthenticationURIparameterstable. AuthenticationURIparameters ThefollowingtablegivesmorecompletedescriptionsoftheparametersacceptedbyGoogle's OAuth2.0authenticationAPI. Parameter Required Description client_id (Required) TheclientIDstringthatyouobtainfromthe APIConsole Credentialspage,asdescribedin ObtainOAuth2.0credentials. nonce (Required) Arandomvaluegeneratedbyyourappthatenablesreplayprotection. response_type (Required) Ifthevalueiscode,launchesa Basicauthorizationcodeflow, requiringaPOSTtothetokenendpointtoobtainthetokens.Ifthevalueis tokenid_tokenorid_tokentoken,launchesan Implicitflow, requiringtheuseofJavaScriptattheredirectURItoretrievetokensfromthe URI#fragmentidentifier. redirect_uri (Required) Determineswheretheresponseissent.Thevalueofthisparametermustexactlymatch oneoftheauthorizedredirectvaluesthatyousetinthe APIConsole Credentialspage(includingtheHTTPorHTTPSscheme, case,andtrailing'/',ifany). scope (Required) Thescopeparametermustbeginwiththeopenidvalueandtheninclude theprofilevalue,theemailvalue,orboth. Iftheprofilescopevalueispresent,theIDtokenmight(butisnot guaranteedto)includetheuser'sdefaultprofileclaims. Iftheemailscopevalueispresent,theIDtokenincludes emailandemail_verifiedclaims. InadditiontotheseOpenID-specificscopes,yourscopeargumentcanalsoincludeother scopevalues.Allscopevaluesmustbespace-separated.Forexample,ifyouwanted per-fileaccesstoauser'sGoogleDrive,yourscopeparametermightbe openidprofileemailhttps://www.googleapis.com/auth/drive.file. Forinformationaboutavailablescopes,see OAuth2.0ScopesforGoogleAPIsorthe documentationfortheGoogleAPIyouwouldliketouse. state (Optional,butstronglyrecommended) Anopaquestringthatisround-trippedintheprotocol;thatistosay,itis returnedasaURIparameterintheBasicflow,andintheURI#fragment identifierintheImplicitflow. Thestatecanbeusefulforcorrelatingrequestsandresponses. Becauseyourredirect_uricanbeguessed,usingastatevalue canincreaseyourassurancethatanincomingconnectionistheresultofan authenticationrequestinitiatedbyyourapp.Ifyou generatearandomstringorencodethehashofsome clientstate(e.g.,acookie)inthisstatevariable,youcanvalidate theresponsetoadditionallyensurethattherequestandresponseoriginatedinthesame browser.Thisprovidesprotectionagainstattackssuchascross-siterequest forgery. access_type (Optional) Theallowedvaluesareofflineandonline.Theeffectis documentedin OfflineAccess;ifanaccess tokenisbeingrequested,theclientdoesnotreceivearefreshtokenunlessavalueof offlineisspecified. display (Optional) AnASCIIstringvalueforspecifyinghowtheauthorizationserverdisplaysthe authenticationandconsentuserinterfacepages.Thefollowingvaluesarespecified,and acceptedbytheGoogleservers,butdonothaveanyeffectonitsbehavior: page,popup,touch,andwap. hd (Optional) StreamlinetheloginprocessforaccountsownedbyaGoogleCloudorganization.By includingtheGoogleCloudorganizationdomain(forexample,mycollege.edu), youcanindicatethattheaccountselectionUIshouldbeoptimizedforaccountsatthat domain.TooptimizeforGoogleCloudorganizationaccountsgenerallyinsteadofjustone GoogleCloudorganizationdomain,setavalueofanasterisk(*): hd=*. Don'trelyonthisUIoptimizationtocontrolwhocanaccessyourapp,asclient-side requestscanbemodified.Besuretovalidatethat thereturnedIDtokenhasanhdclaimvalue thatmatcheswhatyouexpect(e.g.mycolledge.edu).Unliketherequest parameter,theIDtokenhdclaimiscontainedwithinasecuritytokenfrom Google,sothevaluecanbetrusted. include_granted_scopes (Optional) Ifthisparameterisprovidedwiththevaluetrue,andtheauthorizationrequest isgranted,theauthorizationwillincludeanypreviousauthorizationsgrantedtothis user/applicationcombinationforotherscopes;see Incrementalauthorization. NotethatyoucannotdoincrementalauthorizationwiththeInstalledAppflow. login_hint (Optional) Whenyourappknowswhichuseritistryingtoauthenticate,itcanprovidethis parameterasahinttotheauthenticationserver.Passingthishintsuppressestheaccount chooserandeitherpre-fillstheemailboxonthesign-inform,orselectstheproper session(iftheuserisusing multiplesign-in), whichcanhelpyouavoidproblemsthatoccurifyourapplogsinthewronguseraccount. Thevaluecanbeeitheranemailaddressorthesubstring,whichis equivalenttotheuser'sGoogleID. prompt (Optional) Aspace-delimitedlistofstringvaluesthatspecifieswhethertheauthorizationserver promptstheuserforreauthenticationandconsent.Thepossiblevaluesare: none Theauthorizationserverdoesnotdisplayanyauthenticationoruserconsent screens;itwillreturnanerroriftheuserisnotalreadyauthenticatedandhas notpre-configuredconsentfortherequestedscopes.Youcanusenone tocheckforexistingauthenticationand/orconsent. consent Theauthorizationserverpromptstheuserforconsentbeforereturninginformation totheclient. select_account Theauthorizationserverpromptstheusertoselectauseraccount.Thisallowsa userwhohasmultipleaccountsattheauthorizationservertoselectamongstthe multipleaccountsthattheymayhavecurrentsessionsfor. Ifnovalueisspecifiedandtheuserhasnotpreviouslyauthorizedaccess,thenthe userisshownaconsentscreen. ValidatinganIDtoken YouneedtovalidateallIDtokensonyourserverunlessyouknowthattheycamedirectlyfrom Google.Forexample,yourservermustverifyasauthenticanyIDtokensitreceivesfromyour clientapps. ThefollowingarecommonsituationswhereyoumightsendIDtokenstoyourserver: SendingIDtokenswithrequeststhatneedtobeauthenticated.TheIDtokenstellyouthe particularusermakingtherequestandforwhichclientthatIDtokenwasgranted. IDtokensaresensitiveandcanbemisusedifintercepted.Youmustensurethatthesetokens arehandledsecurelybytransmittingthemonlyoverHTTPSandonlyviaPOSTdataorwithin requestheaders.IfyoustoreIDtokensonyourserver,youmustalsostorethemsecurely. OnethingthatmakesIDtokensusefulisthatfactthatyoucanpassthemarounddifferent componentsofyourapp.ThesecomponentscanuseanIDtokenasalightweightauthentication mechanismauthenticatingtheappandtheuser.Butbeforeyoucanusetheinformationinthe IDtokenorrelyonitasanassertionthattheuserhasauthenticated,you mustvalidateit. ValidationofanIDtokenrequiresseveralsteps: VerifythattheIDtokenisproperlysignedbytheissuer.Google-issuedtokensaresigned usingoneofthecertificatesfoundattheURIspecifiedinthejwks_urimetadata valueoftheDiscoverydocument. VerifythatthevalueoftheissclaimintheIDtokenisequalto https://accounts.google.comoraccounts.google.com. VerifythatthevalueoftheaudclaimintheIDtokenisequaltoyourapp's clientID. Verifythattheexpirytime(expclaim)oftheIDtokenhasnotpassed. Ifyouspecifiedahdparametervalueintherequest,verifythat theIDtokenhasahdclaimthatmatchesanaccepteddomainassociatedwitha GoogleCloudorganization. Steps2to5involveonlystringanddatecomparisonswhicharequitestraightforward,sowe won'tdetailthemhere. Thefirststepismorecomplex,andinvolvescryptographicsignaturechecking.For debuggingpurposes,youcanuseGoogle'stokeninfoendpointtocompare againstlocalprocessingimplementedonyourserverordevice.SupposeyourIDtoken'svalueis XYZ123.ThenyouwoulddereferencetheURI https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123.Ifthetoken signatureisvalid,theresponsewouldbetheJWTpayloadinitsdecodedJSONobjectform. Thetokeninfoendpointisusefulfordebuggingbutforproduction purposes,retrieveGoogle'spublickeysfromthekeysendpointandperformthevalidation locally.YoushouldretrievethekeysURIfromtheDiscoverydocument usingthejwks_urimetadatavalue.Requeststothedebuggingendpointmaybe throttledorotherwisesubjecttointermittenterrors. SinceGooglechangesitspublickeysonlyinfrequently,youcancachethemusingthecache directivesoftheHTTPresponseand,inthevastmajorityofcases,performlocalvalidation muchmoreefficientlythanbyusingthetokeninfoendpoint.Thisvalidation requiresretrievingandparsingcertificates,andmakingtheappropriatecryptographiccallsto checkthesignature.Fortunately,therearewell-debuggedlibrariesavailableinawidevariety oflanguagestoaccomplishthis(seejwt.io). Obtaininguserprofileinformation Toobtainadditionalprofileinformationabouttheuser,youcanusetheaccesstoken (whichyourapplicationreceivesduringthe authenticationflow)andthe OpenIDConnectstandard: TobeOpenID-compliant,youmustincludethe openidprofile scopevaluesinyourauthenticationrequest. Ifyouwanttheuser'semailaddresstobeincluded,youcanspecifyanadditionalscope valueofemail. Tospecifybothprofileandemail,youcanincludethefollowing parameterinyourauthenticationrequestURI: scope=openid%20profile%20email AddyouraccesstokentotheauthorizationheaderandmakeanHTTPSGETrequest totheuserinfoendpoint,whichyoushouldretrievefromthe Discoverydocumentusingtheuserinfo_endpointmetadata value.Theuserinforesponseincludesinformationabouttheuser,asdescribedin OpenIDConnectStandardClaims andtheclaims_supportedmetadatavalueoftheDiscoverydocument.Usersortheir organizationsmaychoosetosupplyorwithholdcertainfields,soyoumightnotget informationforeveryfieldforyourauthorizedscopesofaccess. TheDiscoverydocument TheOpenIDConnectprotocolrequirestheuseofmultipleendpointsforauthenticatingusers, andforrequestingresourcesincludingtokens,userinformation,andpublickeys. Tosimplifyimplementationsandincreaseflexibility,OpenIDConnectallowstheuseofa "Discoverydocument,"aJSONdocumentfoundatawell-knownlocationcontainingkey-valuepairs whichprovidedetailsabouttheOpenIDConnectprovider'sconfiguration,includingtheURIsofthe authorization,token,revocation,userinfo,andpublic-keysendpoints. TheDiscoverydocumentforGoogle'sOpenIDConnectservicemayberetrievedfrom: https://accounts.google.com/.well-known/openid-configuration TouseGoogle'sOpenIDConnectservices,youshouldhard-codetheDiscovery-documentURI (https://accounts.google.com/.well-known/openid-configuration)intoyourapplication. Yourapplicationfetchesthedocument,appliescachingrulesintheresponse,thenretrieves endpointURIsfromitasneeded.Forexample,toauthenticateauser,yourcodewouldretrievethe authorization_endpointmetadatavalue (https://accounts.google.com/o/oauth2/v2/authintheexamplebelow) asthebaseURIforauthenticationrequeststhataresenttoGoogle. Hereisanexampleofsuchadocument;thefieldnamesarethosespecifiedin OpenIDConnectDiscovery1.0 (refertothatdocumentfortheirmeanings). Thevaluesarepurelyillustrativeandmightchange,althoughtheyarecopiedfromarecent versionoftheactualGoogleDiscoverydocument: { "issuer":"https://accounts.google.com", "authorization_endpoint":"https://accounts.google.com/o/oauth2/v2/auth", "device_authorization_endpoint":"https://oauth2.googleapis.com/device/code", "token_endpoint":"https://oauth2.googleapis.com/token", "userinfo_endpoint":"https://openidconnect.googleapis.com/v1/userinfo", "revocation_endpoint":"https://oauth2.googleapis.com/revoke", "jwks_uri":"https://www.googleapis.com/oauth2/v3/certs", "response_types_supported":[ "code", "token", "id_token", "codetoken", "codeid_token", "tokenid_token", "codetokenid_token", "none" ], "subject_types_supported":[ "public" ], "id_token_signing_alg_values_supported":[ "RS256" ], "scopes_supported":[ "openid", "email", "profile" ], "token_endpoint_auth_methods_supported":[ "client_secret_post", "client_secret_basic" ], "claims_supported":[ "aud", "email", "email_verified", "exp", "family_name", "given_name", "iat", "iss", "locale", "name", "picture", "sub" ], "code_challenge_methods_supported":[ "plain", "S256" ] } YoumaybeabletoavoidanHTTPround-tripbycachingthevaluesfromtheDiscoverydocument. StandardHTTPcachingheadersareusedandshouldberespected. Clientlibraries ThefollowingclientlibrariesmakeimplementingOAuth2.0simplerbyintegratingwithpopular frameworks: GoogleAPIsClientLibraryforJava GoogleAPIsClientLibraryforPython GoogleAPIsClientLibraryfor.NET GoogleAPIsClientLibraryforRuby GoogleAPIsClientLibraryforPHP OAuth2.0LibraryforGoogleWebToolkit GoogleToolboxforMacOAuth2.0Controllers OpenIDConnectcompliance Google'sOAuth2.0authenticationsystemsupportsthe requiredfeaturesofthe OpenIDConnectCorespecification. AnyclientwhichisdesignedtoworkwithOpenIDConnectshouldinteroperatewiththisservice (withtheexceptionofthe OpenIDRequestObject). Sendfeedback Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2022-03-25UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] Needtotellusmore? GitHub Forkoursamplesandtrythemyourself StackOverflow Askaquestionunderthegoogle-oauthtag Blog ThelatestnewsontheGoogleDevelopersblog ProductInfo TermsofService APIsUserDataPolicy BrandingGuidelines StackOverflow GoogleIdentity SignInWithGoogle GoogleOAuth2.0andOpenIDConnect GoogleAccountLinking Developerconsoles GoogleAPIConsole GoogleCloudPlatformConsole GooglePlayConsole FirebaseConsole ActionsonGoogleConsole CastSDKDeveloperConsole ChromeWebStoreDashboard Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe Language English BahasaIndonesia Deutsch Español Español–AméricaLatina Français Italiano Polski Português–Brasil TiếngViệt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文–简体 中文–繁體 日本語 한국어
延伸文章資訊
- 1從Azure AD 應用程式資源庫設定OpenID Connect OAuth 應用 ...
移至[企業應用程式] >[所有應用程式] 。 The Enterprise applications blade. 選取對話方塊頂端的[新增應用程式] 。 The New application...
- 2Using OpenID Connect to Authenticate to an Android App
Configure OneLogin · Click Add App. · Search for OIDC and select the OpenId Connect (OIDC) app. ·...
- 3OpenID Connect | Google Identity
The implicit flow is used when a client-side application (typically a JavaScript app running in t...
- 4Microsoft 身分識別平台和OpenID Connect 通訊協定
使用OpenID Connect 驗證通訊協定的Microsoft 身分識別平台實作來建置Web 應用 ... by your app &nonce=678910 // Any value, p...
- 5What is OpenID? | OpenID
OpenID allows you to use an existing account to sign in to multiple websites, without needing to ...