[[_identity-brokering]]

== Identity Brokering

An Identity Broker is an intermediary service that connects multiple service providers with different identity providers.
As an intermediary service, the identity broker is responsible to create a trust relationship with an external identity provider in order to use its identities to access internal services exposed by service providers. 

From an user perspective, an identity broker provides an user-centric and centralized way to manage identities across different security domains or realms, where an existing account can be linked with one or more identities from different identity providers or even created based on the identity information obtained from them. 

An identity provider is usually based on a specific protocol in order to authenticate and communicate authentication and authorization information to their users.
It can be a social provider such as Facebook, Google or Twitter, a business partner which you want to allow its users to access your services or a cloud-based identity service that you want to integrate with.
Usually, identity providers are based on the following protocols: 

* `SAML v2.0`            
* `OpenID Connect v1.0`            
* `oAuth v2.0`            

In the next sections we'll see how to configure and use Keycloak as an identity broker, covering some important aspects such as: 

* `Social Authentication`            
* `OpenID Connect v1.0 Brokering`            
* `SAML v2.0 Brokering`            
* `Identity Federation`            

[[_identity_broker_overview]]
=== Overview

When using Keycloak as an identity broker, users are not forced to provide their credentials in order to authenticate in a specific realm.
Instead of that, they are presented with a list of identity providers from where they can pick one and authenticate.
You can also configure a hard-coded default broker.
In this case the user will not be given a choice, but instead be redirected directly the the parent broker.
The following diagram demonstrates the steps involved when using Keycloak to broker an external identity provider: 

        

. User is not authenticated and requests a protected resource in a service provider. 
. The service provider redirects the user to Keycloak to authenticate. 
. At this point the user is presented to the login page where there is a list of identity providers supported by a realm. 
. User selects one of the identity providers by clicking on its respective button or link. 
. Keycloak issues an authentication request to the target identity provider asking for authentication and the user is redirect to the login page or just to a consent page in the identity provider.
  The connection properties and other configuration options for the identity provider were previously set by the administrator in the admin console. 
. User provides his credentials or consent in order to authenticate in the identity provider. 
. Upon a successful authentication by the identity provider, the user is redirected back to Keycloak with an authentication response.
  Usually this response contains a security token that will be used by Keycloak to trust the authentication performed by the identity provider and retrieve information about the user. 
. Now Keycloak is going to check if the response from the identity provider is valid.
  If valid, it will create an user or just skip that if the user already exists.
  If it is a new user, Keycloak may ask informations about the user to the identity provider (or just read that from a security token) and create the user locally.
  This is what we call _identity federation_.
  If the user already exists Keycloak may ask him to link the identity returned from the identity provider with his existing account.
  A process that we call _account linking_.
  What exactly is done is configurable and can be specified by setup of <<_identity_broker_first_login,First Login Flow>> . At the end of this step, Keycloak authenticates the user and issues its own token in order to access the requested resource in the service provider. 
. Once the user is locally authenticated, Keycloak redirects the user to the service provider by sending the token previously issued during the local authentication. 
. The service provider receives the token from Keycloak and allows access to the protected resource. 

There are some variations of this flow that we will talk about later.
For instance, instead of present a list of identity providers, the service provider can automatically select a specific one to authenticate an user.
Or you can tell Keycloak to force the user to provide additional information before federate his identity. 

NOTE: Different protocols may require different authentication flows.
At this moment, all the identity providers supported by KeyCloak use a flow just like described above.
However, despite the protocol in use, user experience should be pretty much the same. 

As you may notice, at the end of the authentication process Keycloak will always issue its own token to service providers, what means that service providers are completely decoupled from external identity providers.
They don't need to know which protocol (eg.: SAML, OpenID Connect, oAuth, etc) was used or how the user's identity was validated.
They only need to know about Keycloak ! 

=== Configuration

The identity broker configuration is all based on identity providers.
Identity providers are created for each realm and by default they are enabled for every single application.
That means that users from a realm can use any of the registered identity providers when signing in to an application. 

In order to create an identity provider, follow these steps: 

. In the admin console, select a realm.
. On the left side menu, click on `Settings`.
. Select the `Identity Provider` tab on the settings page. 
. You should now be able to see a table that lists all registered identity providers.
  To add a new identity provider, click the select box on the top right of this table and select which type of identity provider you want to create. 

Identity providers are organized in two main categories: 

Social::
  Social providers allows you to enable social authentication to your realm.
  Keycloak makes it easy to let users log in to your application using an existing account with a social network.
  Currently Facebook, Google, Twitter, GitHub, LinkedIn, Microsoft and StackOverflow are supported with more planned for the future. 

Protocol-based::
  Protocol-based providers are those that rely on a specific protocol in order to authenticate and authorize users.
  They allow you to connect to any identity provider compliant with a specific protocol.
  Keycloak provides support for SAML v2.0 and OpenID Connect v1.0 protocols.
  It makes it easy to configure and broker any identity provider based on these open standards. 

Although each type of identity provider has its own configuration options, all of them share some very common configuration.
Regardless the identity provider you are creating, you'll see the following configuration options avaiable: 

.Common Configuration
[cols="1,1", options="header"]
|===
| 
                            Configuration
                        
| 
                            Description
                        
| 
                            Alias
                        
| 
                            The alias is an unique identifier for an identity provider. It is used to reference internally an identity provider.
                            Some protocols require a redirect uri or callback url in order to communicate with an identity provider. For instance, OpenID Connect.
                            In this case, the alias is used to build the redirect uri.
                            Every single identity provider must have an alias. For example, facebook, google, idp.acme.com, etc.
                        

| 
                            Name
                        

| 
                            Enabled
                        

| 
                            Authenticate By Default
                        
| 
                            If enabled, Keycloak will automatically redirect to this identity provider even before displaying login screen.
                            In other words, steps 3 and 4 from the base flow are skipped.
                        

| 
                            Store Tokens
                        

| 
                            Stored Tokens Readable
                        
| 
                            Automatically assigns a broker.read-token role that allows the user
                            to access any stored external tokens via the broker service.
                        

| 
                            Trust email
                        

| 
                            GUI order
                        

| 
                            First Login Flow
                        
| 
                            Alias of authentication flow, which is triggered during first login with this identity provider. Term First Login
                            means that there is not yet existing Keycloak account linked with the authenticated identity provider account.
                            More details in First Login section.
                        

| 
                            Post Login Flow
                        
|===

On the next sections, we'll see how to configure each type of identity provider individually. 

=== Social Identity Providers

Forcing users to register to your realm when they want to access applications is hard.
So is trying to remember yet another username and password combination.
Social identity providers makes it easy for users to register on your realm and quickly sign in using a social network.
Keycloak provides built-in support for the most common social networks out there, such as Google, Facebook, Twitter, Github, LinkedId, Microsoft and StackOverflow. 

==== Google

To enable login with Google you first have to create a project and a client in the https://cloud.google.com/console/project[Google Developer Console].
Then you need to copy the client id and secret into the Keycloak Admin Console. 

Let's see first how to create a project with Google. 

. Log in to the https://cloud.google.com/console/project[Google Developer Console].
  Click the `Create Project` button.
  Use any value for `Project name` and `Project ID` you want, then click the `Create` button.
  Wait for the project to be created (this may take a while). 
. Once the project has been created click on `APIs & auth` in sidebar on the left.
  To retrieve user profiles the `Google+ API` has to be enabled.
  Scroll down to find it in the list.
  If its status is `OFF`, click on `OFF` to enable it (it should move to the top of the list and the status should be `ON`). 
. Now click on the `Consent screen` link on the sidebar menu on the left.
  You must specify a project name and choose an email for the consent screen.
  Otherwise users will get a login error.
  There's other things you can configure here like what the consent screen looks like.
  Feel free to play around with this. 
. Now click `Credentials` in the sidebar on the left.
  Then click `Create New Client ID`.
  Select `Web application` as `Application type`.
  Empty the `Authorized Javascript origins` textarea.
  Click the `Create Client ID` button. 
. Copy `Client ID` and `Client secret`. 

Now that you have the client id and secret, you can proceed with the creation of a Google Identity Provider in Keycloak.
As follows: 

. Select the `Google` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provided. 
. Copy the client id and secret to their corresponding fields in the Keycloak Admin Console.
  Click `Save`. 

Once you create the identity provider in Keycloak, you must update your Google project with the redirect url that was generated to your identity provider. 

. Open the Google Developer Console and select your project.
  Click `Credentials` in the sidebar on the left.
  In `Authorized redirect URI` insert the redirect uri created by Keycloak.
  The redirect uri usually have the following format: `http://{host}:{port}/auth/realms/{realm}/broker/{provider_alias}`. 

NOTE: You can always get the redirect url for a specific identity provider from the table presented when you click on the 'Identity Provider' tab in _Realm > Settings_. 

That is it! This is pretty much what you need to do in order to setup this identity provider. 

The table below lists some additional configuration options you may use when configuring this provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                                Configuration
                            
| 
                                Description
                            
| 
                                Default Scopes
                            
| 
                                Allows you to manually specify the scopes that users must authorize when authenticating with this provider. For a complete list of scopes, please take a look at https://developers.google.com/oauthplayground/. By default, Keycloak uses the following scopes: openid profile email
                            
|===

==== Facebook

To enable login with Facebook you first have to create an application in the https://developers.facebook.com/[Facebook Developer Console].
Then you need to copy the client id and secret into the Keycloak Admin Console. 

Let's see first how to create an application with Facebook. 

. Log in to the https://developers.facebook.com/[Facebook Developer Console].
  Click `Apps` in the menu and select `Create a New App`.
  Use any value for `Display Name` and `Category` you want, then click the `Create App` button.
  Wait for the project to be created (this may take a while). If after creating the app you are not redirected to the app settings, click on `Apps` in the menu and select the app you created. 
. Once the app has been created click on `Settings` in sidebar on the left.
  You must specify a contact email.
  Save your changes.
  Then click on `Advanced`.
  Under `Security` make sure `Client OAuth Login` is enabled.
  Scroll down and click on the `Save Changes` button. 
. Click `Status & Review` and select `YES` for `Do you want
  to make this app and all its live features available to the general public?`.
  You will not be able to set this until you have provided a contact email in the general settings of this application. 
. Click `Basic`.
  Copy `App ID` and `App Secret`                        (click `show`) from the https://developers.facebook.com/[Facebook Developer Console]. 

Now that you have the client id and secret, you can proceed with the creation of a Facebook Identity Provider in Keycloak.
As follows: 

. Select the `Facebook` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provided. 
. Copy the client id and secret to their corresponding fields in the Keycloak Admin Console.
  Click `Save`. 

Once you create the identity provider in Keycloak, you must update your Facebook application with the redirect url that was generated to your identity provider. 

. Open the Facebook Developer Console and select your application.
  Click on `Advanced`.
  Under `Security` make sure `Client OAuth Login` is enabled.
  In `Valid OAuth redirect URIs` insert the redirect uri created by Keycloak.
  The redirect uri usually have the following format: `http://{host}:{port}/auth/realms/{realm}/broker/{provider_alias}`. 

NOTE: You can always get the redirect url for a specific identity provider from the table presented when you click on the 'Identity Provider' tab in _Realm > Settings_. 

That is it! This pretty much what you need to do in order to setup this identity 		provider. 

The table below lists some additional configuration options you may use when configuring this provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                                Configuration
                            
| 
                                Description
                            
| 
                                Default Scopes
                            
| 
                                Allows you to manually specify the scopes that users must authorize when authenticating with this provider. For a complete list of scopes, please take a look at https://developers.facebook.com/docs/graph-api. By default, Keycloak uses the following scopes: email
                            
|===

==== Twitter

To enable login with Twtter you first have to create an application in the https://dev.twitter.com/apps[Twitter Developer Console].
Then you need to copy the consumer key and secret into the Keycloak Admin Console. 

Let's see first how to create an application with Twitter. 

. Log in to the https://dev.twitter.com/apps[Twitter Developer Console].
  Click the `Create a new application` button.
  Use any value for `Name`, `Description` and `Website` you want.
  Insert the social callback url in `Callback URL`.
  Then click `Create your Twitter application`. 
. Now click on `Settings` and tick the box `Allow this application to be used to Sign in with Twitter`, then click on `Update this Twitter application's settings`. 
. Now click `API Keys` tab.
  Copy `API key` and `API secret` from the https://dev.twitter.com/apps[Twitter Developer Console]. 

NOTE: Twitter doesn't allow `localhost` in the redirect URI.
To test on a local server replace `localhost` with `127.0.0.1`. 

Now that you have the client id and secret, you can proceed with the creation of a Twitter Identity Provider in Keycloak.
As follows: 

. Select the `Twitter` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provided. 
. Copy the client id and secret to their corresponding fields in the Keycloak Admin Console.
  Click `Save`. 

That is it! This pretty much what you need to do in order to setup this identity 		provider. 

The table below lists some additional configuration options you may use when configuring this provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                                Configuration
                            
| 
                                Description
                            
| 
                                Default Scopes
                            
|===

==== Github

To enable login with GitHub you first have to create an application in https://github.com/settings/applications[GitHub Settings].
Then you need to copy the client id and secret into the Keycloak Admin Console. 

Let's see first how to create an application with GitHub. 

. Log in to https://github.com/settings/applications[GitHub Settings].
  Click the `Register new application` button.
  Use any value for `Application name`, `Homepage URL` and `Application Description` you want.
  Click the `Register application` button. 
. Copy `Client ID` and `Client Secret` from the https://github.com/settings/applications[GitHub Settings]. 

Now that you have the client id and secret, you can proceed with the creation of a Github Identity Provider in Keycloak.
As follows: 

. Select the `Github` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provided. 
. Copy the client id and secret to their corresponding fields in the Keycloak Admin Console.
  Click `Save`. 

Once you create the identity provider in Keycloak, you must update your GitHub application with the redirect url that was generated to your identity provider. 

. Open the GitHub Settings and select your application.
  In `Authorization callback URL`                        insert the redirect uri created by Keycloak.
  The redirect uri usually have the following format: `http://{host}:{port}/auth/realms/{realm}/broker/{provider_alias}`. 

NOTE: You can always get the redirect url for a specific identity provider from the table presented when you click on the 'Identity Provider' tab in _Realm > Settings_. 

That is it! This pretty much what you need to do in order to setup this identity 		provider. 

The table below lists some additional configuration options you may use when configuring this provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                                Configuration
                            
| 
                                Description
                            
| 
                                Default Scopes
                            
| 
                                Allows you to manually specify the scopes that users must authorize when authenticating with this provider. For a complete list of scopes, please take a look at https://developer.github.com/v3/oauth/#scopes. By default, Keycloak uses the following scopes: user:email
                            
|===

==== LinkedIn

To enable login with LinkedIn you first have to create an application in https://www.linkedin.com/secure/developer[LinkedIn Developer Network].
Then you need to copy the client id and secret into the Keycloak Admin Console. 

Let's see first how to create an application with LinkedIn. 

. Log in to https://www.linkedin.com/secure/developer[LinkedIn Developer Network].
  Click the `Add New Application` link.
  Use any value for `Application Name`, `Website URL`, `Description`, `Developer Contact Email` and `Phone` you want.
  Select `r_basicprofile` and `r_emailaddress` in the `Default Scope` section.
  Click the `Add Application` button. 
. Copy `Consumer Key / API Key` and `Consumer Secret / Secret Key` from the shown page. 

Now that you have the client id and secret, you can proceed with the creation of a LinkedIn Identity Provider in Keycloak.
As follows: 

. Select the `LinkedIn` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provided. 
. Copy the client id and secret to their corresponding fields in the Keycloak Admin Console.
  Click `Save`. 

Once you create the identity provider in Keycloak, you must update your LinkedIn application with the redirect url that was generated to your identity provider. 

. Open the LinkedIn Developer Network and select your application.
  In `OAuth 2.0 Redirect URLs`                        insert the redirect uri created by Keycloak.
  The redirect uri usually have the following format: `http://{host}:{port}/auth/realms/{realm}/broker/{provider_alias}/endpoint`. 

NOTE: You can always get the redirect url for a specific identity provider from the table presented when you click on the 'Identity Provider' tab in _Realm > Settings_. 

That is it! This pretty much what you need to do in order to setup this identity provider. 

The table below lists some additional configuration options you may use when configuring this provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                                Configuration
                            
| 
                                Description
                            
| 
                                Default Scopes
                            
| 
                                Allows you to manually specify the scopes that users must authorize when authenticating with this provider. 
                                For a complete list of scopes, please take a look at application configuration in LinkedIn Developer Network. By default, Keycloak uses the following scopes: r_basicprofile r_emailaddress
                            
|===

==== Microsoft

To enable login with Microsoft account you first have to register an OAuth application on https://account.live.com/developers/applications/index[Microsoft account Developer Center].
Then you need to copy the client id and secret into the Keycloak Admin Console. 

Let's see first how to create an application with Microsoft. 

. Go to https://account.live.com/developers/applications/create[create new application on Microsoft account Developer Center] url and login here.
  Use any value for `Application Name`, `Application Logo` and `URLs` you want.
  In `API Settings` set `Target Domain` to the domain where your Keycloak instance runs. 
. Copy `Client Id` and `Client Secret` from `App Settings` page. 

Now that you have the client id and secret you can proceed with the creation of a Microsoft Identity Provider in Keycloak.
As follows: 

. Select the `Microsoft` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provided. 
. Copy the client id and client secret to their corresponding fields in the Keycloak Admin Console.
  Click `Save`. 

Once you create the identity provider in Keycloak, you must update your Microsoft application with the redirect url that was generated to your identity provider. 

. Open the Microsoft account Developer Center and select `API Settings` of your application.
  In `Redirect URLs`                        insert the redirect uri created by Keycloak.
  The redirect uri usually have the following format: `http://{host}:{port}/auth/realms/{realm}/broker/microsoft/endpoint`. 

NOTE: You can always get the redirect url for a specific identity provider from the table presented when you click on the 'Identity Provider' tab in _Realm > Settings_. 

That is it! This pretty much what you need to do in order to setup this identity provider. 

The table below lists some additional configuration options you may use when configuring this provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                                Configuration
                            
| 
                                Description
                            
| 
                                Default Scopes
                            
| 
                                Allows you to manually specify the scopes that users must authorize when authenticating with this provider. For a complete list of scopes, please take a look at https://msdn.microsoft.com/en-us/library/hh243646.aspx. By default, Keycloak uses the following scopes: wl.basic,wl.emails
                            
|===

==== StackOverflow

To enable login with StackOverflow you first have to register an OAuth application on https://stackapps.com/[StackApps].
Then you need to copy the client id, secret and key into the Keycloak Admin Console. 

Let's see first how to create an application with StackOverflow. 

. Go to http://stackapps.com/apps/oauth/register[registering your application on Stack Apps] url and login here.
  Use any value for `Application Name`, `Application Website` and `Description` you want.
  Set `OAuth Domain` to the domain where your Keycloak instance runs.
  Click the `Register Your Application` button. 
. Copy `Client Id`, `Client Secret` and `Key` from the shown page. 

Now that you have the client id, secret and key, you can proceed with the creation of a StackOverflow Identity Provider in Keycloak.
As follows: 

. Select the `StackOverflow` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provided. 
. Copy the client id, client secret and key to their corresponding fields in the Keycloak Admin Console.
  Click `Save`. 

That is it! This pretty much what you need to do in order to setup this identity provider. 

The table below lists some additional configuration options you may use when configuring this provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                                Configuration
                            
| 
                                Description
                            
| 
                                Default Scopes
                            
| 
                                Allows you to manually specify the scopes that users must authorize when authenticating with this provider. 
                                For a complete list of scopes, please take a look at application configuration in StackExchange API Authentication documentation. Keycloak uses the empty scope by default.
                            
|===

=== SAML v2.0 Identity Providers

Keycloak can broker identity providers based on the SAML v2.0 protocol. 

In order to configure a SAML identity provider, follow these steps: 

. Select the `SAML v2.0` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provider. 

When configuring a SAML identity provider you are presented with different configuration options in order to properly communicate and integrate with the external identity provider.
In this case, you must keep in mind that Keycloak will act as an Service Provider that issues authentication requests(AuthnRequest) to the external identity provider. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                            Configuration
                        
| 
                            Description
                        
| 
                            Import IdP SAML Metadata
                        

| 
                            Single Sign-On Service Url
                        

| 
                            Single Logout Service Url
                        

| 
                            Backchannel Logout
                        

| 
                            NameID Policy Format
                        

| 
                            Validating X509 Certificate
                        

| 
                            Want AuthnRequests Signed
                        

| 
                            Force Authentication
                        

| 
                            Validate Signature
                        

| 
                            HTTP-POST Binding Response
                        

| 
                            HTTP-POST Binding for AuthnReques
                        
|===

You can also import all this configuration data by providing a URL or XML file that points to the entity descriptor of the external SAML IDP you want to connect to. 

Once you create a SAML provider, there is an `EXPORT` button that appears when viewing that provider.
Clicking this button will export a SAML entity descriptor which you can use to 

==== SP Descriptor

The SAML SP Descriptor XML file for the broker is available publically by going to this URL

[source]
----

                http[s]://{host:port}/auth/realms/{realm-name}/broker/{broker-alias}/endpoint/descriptor
----

This URL is useful if you need to import this information into an IDP that needs or is more user friendly to load from a remote URL. 

=== OpenID Connect v1.0 Identity Providers

Keycloak can broker identity providers based on the OpenID Connect v1.0 protocol. 

In order to configure a OIDC identity provider, follow these steps: 

. Select the `OpenID Connect v1.0` identity provider from the drop-down box on the top right corner of the identity providers table in Keycloak's Admin Console.
  You should be presented with a specific page to configure the selected provider. 

When configuring an OIDC identity provider you are presented with different configuration options in order to send authentication requests to the external identity provider.
In this case, the brokered identity provider must support the Authorization Code Flow (as defined by the specification) in order to authenticate the user and authorize access for the scopes specified in the configuration. 

.Configuration Options
[cols="1,1", options="header"]
|===
| 
                            Configuration
                        
| 
                            Description
                        
| 
                            Authorization Url
                        

| 
                            Token Url
                        

| 
                            Logout Url
                        

| 
                            Backchannel Logout
                        

| 
                            User Info Url
                        

| 
                            Client ID
                        

| 
                            Client Secret
                        

| 
                            Issuer
                        

| 
                            Default Scopes
                        
| 
                            Allows you to specify additional scopes when asking for user authentication and consent. By default, scope openid is always appended to the list of the scopes.
                        

| 
                            Prompt
                        
|===

You can also import all this configuration data by providing a URL or file that points to OpenID Provider Metadata (see OIDC Discovery specification) 

=== Retrieving Tokens from Identity Providers

Keycloak allows you to store tokens and responses from identity providers during the authentication process.
For that, you can use the `Store Token` configuration option, as mentioned before. 

It also allows you to retrieve these tokens and responses once the user is authenticated in order to use their information or use them to invoke external resources protected by these tokens.
The latter case is usually related with social providers, where you usually need to use their tokens to invoke methods on their APIs. 

To retrieve a token for a particular identity provider you need to send a request as follows: 

[source,java]
----
GET /auth/realms/{realm}/broker/{provider_alias}/token HTTP/1.1
Host: localhost:8080
Authorization: Bearer {keycloak_access_token}
----

In this case, given that you are accessing an protected service in Keycloak, you need to send the access token issued by Keycloak during the user authentication. 

By default, the Keycloak access token issued for the application can't be automatically used for retrieve thirdparty token.
A user will have to have the `broker.read-token` role.
The client will also have to have that role in its scope.
In the broker configuration page you can automatically assign this role to newly imported users by turning on the `Stored Tokens Readable` switch. 

NOTE: If your application is not at the same origin as the authentication server, make sure you have properly configured CORS. 

=== Automatically Select and Identity Provider

Each Identity provider has option `Authenticate By Default`, which allows that Identity provider is automatically selected during authentication.
User won't even see Keycloak login page, but is automatically redirected to the identity provider. 

Applications can also automatically select an identity provider in order to authenticate an user.
Selection per application is preferred over `Authenticate By Default` option if you need more control on when exactly is Identity provider automatically selected. 

Keycloak supports a specific HTTP query parameter that you can use as a hint to tell the server which identity provider should be used to authenticate the user. 

For that, you can append the `kc_idp_hint` as a query parameter to your application url, as follows: 

[source,java]
----
GET /myapplication.com?kc_idp_hint=facebook HTTP/1.1
Host: localhost:8080
----

In this case, is expected that your realm has an identity provider with an alias `facebook`. 

If you are using `keycloak.js` adapter, you can also achieve the same behavior: 

[source,java]
----
var keycloak = new Keycloak('keycloak.json');

keycloak.createLoginUrl({
	idpHint: 'facebook'
});
----

=== Mapping/Importing SAML and OIDC Metadata

You can import SAML assertion data, OpenID Connect ID Token claims, and Keycloak access token claims into new users that are imported from a brokered IDP.
After you configure a broker, you'll see a `Mappers`            button appear.
Click on that and you'll get to the list of mappers that are assigned to this broker.
There is a `Create` button on this page.
Clicking on this create button allows you to create a broker mapper.
Broker mappers can import SAML attributes or OIDC ID/Access token claims into user attributes.
You can assign a role mapping to a user if a claim or external role exists.
There's a bunch of options here so just mouse over the tool tips to see what each mapper can do for you. 

=== Mapping/Importing User profile data from Social Identity Provider

You can import user profile data provided by social identity providers like Google, GitHub, LinkedIn, Microsoft, Stackoverflow and Facebook  into new Keycloak user created from given social accounts.
After you configure a broker, you'll see a `Mappers`            button appear.
Click on that and you'll get to the list of mappers that are assigned to this broker.
There is a `Create` button on this page.
Clicking on this create button allows you to create a broker mapper.
"Attribute Importer" mapper allows you to define path in JSON user profile data provided by the provider to get value from.
You can use dot notation for nesting and square brackets to access fields in array by index.
For example 'contact.address[0].country'.  Then you can define name of Keycloak's user profile attribute this value is stored into. 

To investigate structure of user profile JSON data provided by social providers you can enable `DEBUG` level for  logger `org.keycloak.social.user_profile_dump` and login using given provider.
Then you can find user profile  JSON structure in Keycloak log file.
 

=== User Session Data

After a user logs in from the external IDP, there's some additional user session note data that Keycloak stores that you can access.
This data can be propagated to the client requesting a login via the token or SAML assertion being passed back to it by using an appropriate client mapper. 

BROKER_PROVIDER_ID::
  This is the IDP alias of the broker used to perform the login.         

[[_identity_broker_first_login]]
=== First Login Flow

When Keycloak successfully authenticates user through identity provider (step 8 in <<_identity_broker_overview,Overview>> chapter), there can be two situations: 

. There is already Keycloak user account linked with the authenticated identity provider account.
  In this case, Keycloak will just authenticate as the existing user and redirect back to application (step 9 in <<_identity_broker_overview,Overview>> chapter). 
. There is not yet existing Keycloak user account linked with the identity provider account.
  This situation is more tricky.
  Usually you just want to register new account into Keycloak database, but what if there is existing Keycloak account with same email like the identity provider account? Automatically link identity provider account with existing Keycloak account is not very good option as there are possible security flaws related to that...         

Because we had various requirements what to do in second case, we changed the behaviour to be flexible and configurable through <<_auth_spi,Authentication Flows SPI>>.
In admin console in Identity provider settings, there is option `First Login Flow`, which allows you to choose, which workflow will be used after "first login" with this identity provider account.
By default it points to `first broker login` flow, but you can configure and use your own flow and use different flows for different identity providers etc. 

The flow itself is configured in admin console under `Authentication` tab.
When you choose `First Broker Login` flow, you will see what authenticators are used by default.
You can either re-configure existing flow (For example disable some authenticators, mark some of them as `required`, configure some authenticators etc). Or you can even create new authentication flow and/or write your own Authenticator implementations and use it in your flow.
See <<_auth_spi,Authentication Flows SPI>> for more details on how to do it. 

For `First Broker Login` case, it might be useful if your Authenticator is subclass of `org.keycloak.authentication.authenticators.broker.AbstractIdpAuthenticator`            so you have access to all details about authenticated Identity provider account.
But it's not a requirement. 

==== Default First Login Flow

Let's describe the default behaviour provided by `First Broker Login` flow.
There are those authenticators: 

Review Profile::
  This authenticator might display the profile info page, where user can review his profile retrieved from identity provider.
  The authenticator is configurable.
  You can set `Update Profile On First Login` option.
  When `On`, users will be always presented with the profile page asking for additional information in order to federate their identities.
  When `missing`, users will be presented with the profile page only if some mandatory information (email, first name, last name) is not provided by identity provider.
  If `Off`, the profile page won't be displayed, unless user clicks in later phase on `Review profile info`                                link (page displayed in later phase by `Confirm Link Existing Account` authenticator) 

Create User If Unique::
  This authenticator checks if there is already existing Keycloak account with same email or username like the account from identity provider.
  If it's not, then authenticator just creates new Keyclok account and link it with identity provider and whole flow is finished.
  Otherwise it goes to the next `Handle Existing Account` subflow.
  If you always want to ensure that there is no duplicated account, you can mark this authenticator as `REQUIRED` . In this case, the user will see the error page if there is existing Keycloak account and user needs to link his identity provider account through Account management. 

Confirm Link Existing Account::
  User will see the info page, that there is existing Keycloak account with same email.
  He can either review his profile again and use different email or username (flow is restarted and goes back to `Review Profile` authenticator). Or he can confirm that he wants to link identity provider account with his existing Keycloak account.
  Disable this authenticator if you don't want users to see this confirmation page, but go straight to linking identity provider account by email verification or re-authentication. 

Verify Existing Account By Email::
  This authenticator is `ALTERNATIVE` by default, so it's used only if realm has SMTP setup configured.
  It will send mail to user, where he can confirm that he wants to link identity provider with his Keycloak account.
  Disable this if you don't want to confirm linking by email, but instead you always want users to reauthenticate with their password (and alternatively OTP). 

Verify Existing Account By Re-authentication::
  This authenticator is used if email authenticator is disabled or non-available (SMTP not configured for realm). It will display login screen where user needs to authenticate with his password to link his Keycloak account with Identity provider.
  User can also re-authenticate with some different identity provider, which is already linked to his keycloak account.
  You can also force users to use OTP, otherwise it's optional and used only if OTP is already set for user account.             

=== Examples

Keycloak provides some useful examples about how to use it as an identity broker.
Take a look at `{KEYCLOAK_HOME}/examples/broker` for more details. 

Each example application has its own README file where you can find additional information about how to configure Keycloak and run it. 
