Keycloak 18.0.2 get id_token_hint for logout url by the API call - jwt

Is it possible with Keycloak 18 to get id_token_hint value, required for logout url via direct API call to the Keycloak server? If so, could you please show how?
Also, is this safe to keep id_token_hint value on the client side, let's say in JWT claim?

I am not sure if I fully understood your question, nonetheless from the OpenID Connect standard (section 2.RP-Initiated Logout) one can read:
This specification defines the following parameters that are used in
the logout request at the Logout Endpoint:
id_token_hint RECOMMENDED. ID Token previously issued by the OP to the
RP passed to the Logout Endpoint as a hint about the End-User's
current authenticated session with the Client. This is used as an
indication of the identity of the End-User that the RP is requesting
be logged out by the OP.
So you need to pass id_token_hint=<id_token>. You get the id token by calling the token endpoint with the scope=openid. For example, when a user logs in via browser if you request includes the scope=openid you will get (along with the refresh and access tokens) the user id token.

Not the best option, but works, and you dont need id_token_hint
when start keycloak add the following parameter to the command line:
kc.sh start --spi-login-protocol-openid-connect-legacy-logout-redirect-uri=true
Still have to confirm the logout when you call logout page,but you can use redirect_uri in the old way.
https://keycloak.lvh.me/realms/airports/protocol/openid-connect/logout?redirect_uri=https%3A%2F%2Foauth2.lvh.me%2Foauth2%2Fsign_out

Related

Keycloak logout response 414

GET /realms/[REALM_NAME]/protocol/openid-connect/logout?post_logout_redirect_uri=[...]&id_token_hint=[..very large jwt-token >4096..]
Response 414 (Uri to long (link)
Keycloak version: v20.0.1
Expected: Successful logout redirect. The above request should response 302.
AFAIK, you should pass an ID token to the id_token_hint and not and access token. From the OpenID Connect standard (section 2.RP-Initiated Logout) one can read:
This specification defines the following parameters that are used in
the logout request at the Logout Endpoint:
id_token_hint RECOMMENDED. ID Token previously issued by the OP to the
RP passed to the Logout Endpoint as a hint about the End-User's
current authenticated session with the Client. This is used as an
indication of the identity of the End-User that the RP is requesting
be logged out by the OP.
So you need to pass id_token_hint=<id_token>. You get the ID token by calling the token endpoint with the scope=openid. For example, when a user logs in via browser if you request includes the scope=openid you will get (along with the refresh and access tokens) the user ID token.
It seems that the logout URI path is to long. The default length of the keycloak quarkus service is 4096 bytes (link).
this occur when Your id_token_hint is to large
Set higher length for quarkus parameter quarkus.http.limits.max-initial-line-length ...
as java parameter -quarkus.http.limits.max-initial-line-length=8192
or environment variable QUARKUS_HTTP_LIMITS_MAX_INITIAL_LINE_LENGTH=8192

What is the proper way to invoke Keycloak's end_session_endpoint

Environment: Keycloak 12.0.4
We plan to allow various OpenIDC-protected applications to initiate a "single sign-out" using Keycloak's end_session_endpoint. In our case, we'd like to provide our own URL that applications will hit when they want to sign-out. That URL will either programmatically invoke the end_session_endpoint or simply redirect the user's browser to that endpoint.
The Keycloak documentation and examples I've seen so far are a bit confusing regarding how to invoke this endpoint. For example, do I need to add a query parameter with the id token as a value? (I noticed, for example, that mod_auth_openidc includes an id_token_hint query param.) I assume this call has to be authenticated, so do I include the client id/secret as the credentials?
Thanks!
You have standard how to call RP-Initiated Logout:
https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RPLogout
An RP requests that the OP log out the End-User by redirecting the End-User's User Agent to the OP's Logout Endpoint.
It is a redirect, not API call, because you very likely wants to delete also IDP session (cookies on used Keycloak domain in your case).
Here's some additional information from the keycloak-user group which I think completely answers the question:
You can look at
https://openid.net/specs/openid-connect-session-1_0-17.html#RPLogout.
From our implementation, we rely on either cookies or the
id_token_hint to identify the user and logout sessions. So you don't
necessarily need to send id_token_hint if cookies are sent when
redirecting the user from your application to Keycloak. You can also
send a state param to match if the logout action sent to your
application originated from a valid logout request.
Note, however, that we don't force the id_token_hint and do not ask
the user for confirmation, as per spec. But there are discussions to
introduce a consent page.
In regards to logout, messages are sent to clients through the
backchannel.
Edit: Here's the actual (latest) RP-initated logout spec: https://openid.net/specs/openid-connect-rpinitiated-1_0.html.
The logout URL needs to be build from
the OpenID Connect end session endpoint
a target redirect URI where the user should be sent after logout, provided as query param post_logout_redirect_uri
The encoded ID token as query param id_token_hint
In Spring it can be built like this:
String logoutLink = UriComponentsBuilder.fromUri(endSessionEndpoint)
.queryParam("post_logout_redirect_uri", logoutUrlEncoded)
.queryParam("id_token_hint",
((OidcUser) authentication.getPrincipal()).getIdToken().getTokenValue())
.build().toUriString();

Why google-oauth API requires redirect-url?

I'm trying to set up an authorization flow with google-oauth2 API.
The task is to authorize users with google accounts in my web-application which consists of frontend and backend parts.
The flow according to the documentation consists of 2 steps:
1) obtaining an auth code
2) exchanging an auth code for a token
In my flow, FE client obtains an auth code from google and submits it to BE, which then exchanges it for a token, so no redirect URL (or sometimes called callback URL) is used.
I do not understand why google API requires me to provide redirect_uri for the second step? Since this step is performed by a server, not a browser, I don't see any sense in this piece of info. The server just calls the POST /oauth2/v4/token google endpoint and receives token in response.
see step 4 at https://developers.google.com/identity/protocols/OpenIDConnect
According to this, it's to guard against stealing the access_token. If a service doesn't check the initial redirect_uri, the authorization code is sent to the hacker's redirect_uri, which can then exchange it for an access_token, i.e. illegal access to the user's account. To actually get the access_token, the redirect_uri is specified again and this time must be checked by the server against the ones that are registered for that application. At that point, the hacker is foiled as the fake redirect_uri doesn't match any of the legal ones. Apparently some servers don't check the redirect_uri during the authorization stage and sending the redirect_uri again when requesting the access_token is meant to provide a final safey check.

Keycloak Silent Authentication

I have a react app that uses Keycloak endpoint token_endpoint to authenticate the user. The problem I'm facing now is how to update/refresh this token. I know I could use a refresh token but that's a bad practice since has security issue when it comes to a web application. It seems to me that the best approach would be to use Silent Authentication.
Unfortunately, I couldn't find any example or documentation that allows me to achieve this. In case you guys have another approach I'm open to suggestions.
Tks
It would consist just of providing the prompt=none parameter on the authentication request as stated in the OpenID Connect 1.0 Core spec:
https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
prompt OPTIONAL.
Space delimited, case sensitive list of ASCII string
values that specifies whether the Authorization Server prompts the
End-User for reauthentication and consent. The defined values are:
none
The Authorization Server MUST NOT display any authentication or
consent user interface pages. An error is returned if an End-User is
not already authenticated or the Client does not have pre-configured
consent for the requested Claims or does not fulfill other conditions
for processing the request. The error code will typically be
login_required, interaction_required, or another code defined in
Section 3.1.2.6. This can be used as a method to check for existing
authentication and/or consent.
Authenticate to obtain an access_token with /auth (prompt=login).
Just call OIDC /token with grant_type=refresh_token to refresh token with the access_token. the new response include access_token, refresh_token and so.
After that you must update them for the new api calls.

Facebook OAuth 2.0 "code" and "token"

Why do you need both a "code" and a "token" in the Facebook OAuth2 authentication flow as described here: https://developers.facebook.com/docs/authentication/ ?
If you look at the OAuth dialog reference (https://developers.facebook.com/docs/reference/dialogs/oauth/), it seems like you only ever use the token to fetch information about the user, and if you specify the response_type parameter as token or code,token, then you get the token on the first time.
Why do you need to get a "code" and then use the code to get a "token" as opposed to getting the token directly?
I guess I'm misunderstanding something basic about how OAuth works, but it seems you avoid the request to https://graph.facebook.com/oauth/access_token entirely if you get the token the first time with the dialog.
Let us take a simple example to differentiate authentication code vs access token.
You as a user want to try a new Facebook app called Highjack.
So you click on the application and the Highjack app asks you to log into your Facebook account. When you are done, Facebook generates an authentication code for you.
This code is then passed to the Highjack server which uses its own FB client id, FB secret and your authentication code to get an access token.
In the above example the authentication code is confirming you as a user is a valid FB user. But the second steps says "you as a FB user is giving access to the Highjack app for certain resources".
If the Highjack app wanted implicit grant (i.e direct access token), then the access token would be visible to you also since it is being exchanged with the browser. This means you can now call all Facebook APIs on behalf of Highjack using the access token. (You can only use the access token to get your personal information but Facebook has no way of knowing who is calling their APIs.)
Since we have 2 parties (You and Highjack) authenticating with Facebook we have this 2 fold mechanism.
Borrowed shamelessly from Salesforce Documentation:
Authorization Code
An authorization code is a short-lived token representing the user's access grant, created by the authorization server and passed to the client application via the browser. The client application sends the authorization code to the authorization server to obtain an access token and, optionally, a refresh token.
Access Token
The access token is used by the client to make authenticated requests on behalf of the end user. It has a longer lifetime than the authorization code, typically on the order of minutes or hours. When the access token expires, attempts to use it will fail, and a new access token must be obtained via a refresh token.
From the OAuth 2.0 Spec:
The authorization code provides a few important security benefits
such as the ability to authenticate the client, and the transmission
of the access token directly to the client without passing it through
the resource owner's user-agent, potentially exposing it to others,
including the resource owner.
So, basically - the main reason is to limit the # of actors getting the access token.
"token" response is intended primarily for clients that live in the browser (e.g.: JavaScript client).
Answer) You need/want both the code and token for extra security.
According to Nate Barbettini we want the extra step of exchanging the authentication code for the access token, because the authentication code can be used in the front channel (less secure), and the access token can be used in the back channel (more secure).
Thus, the security benefit is that the access token isn't exposed to the browser, and thus cannot be intercepted/grabbed from a browser. We trust the web server more, which communicates via back channels. The access token, which is secret, can then remain on the web server, and not be exposed to the browser (i.e. front channels).
For more information, watch this fantastic video:
OAuth 2.0 and OpenID Connect (in plain English)
https://youtu.be/996OiexHze0?t=26m30s (Start 26 mins)
If you look at the flow of Authorization Code OAuth type, yes, there are actuary two steps:
<user_session_id, client_id> => authorization_code
<client_id, redirect_uri, authorization_code, client_secret> => access_token, refresh_token
In step1: the user tells the OAuth Server that "I want to auth this client (client_id) to access my resource. Here is my authentication (user_session_id or what else)"
In step2: the client (client_id) tells the OAuth server that "I've got the user the authorization (authorization_code), please give me an access token for later access. And this is my authentication (client_id & client_secret)"
You see, if we omit step 2, then there is no guarantee for client authentication. Any client can invoke step1 with a different client_id and get an access token for that client_id instead of its own. That's why we need step2.
If you really want to combine step1 and step2, you can do something like this:
<client_id, redirect_uri, client_secret> => access_token, refresh_token
We use this approach in our Open API Platform, and we haven't find any security problem yet.
BTW, there is actually an Implicit Grant type, that is:
<client_id, redirect_uri> => access_token, refresh_token
It is generally applicable to client only application which have no server backend. In that case, the OAuth server must ensure that the redirect URI belongs to that client (same with the register redirect_uri, for example).
The mix-up came because the user on behalf of himself and not the client app authenticate against the authorization server (i.e. facebook).
Its much simple to secure the client app (with https) then the user-agent (browser).
Here is the original formulation from IETF-oauth (https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-threatmodel-08#section-3.4):
3.4. Authorization Code
An authorization code represents the intermediate result of a
successful end-user authorization process and is used by the client
to obtain access and refresh token. Authorization codes are sent to
the client's redirection URI instead of tokens for two purposes.
Browser-based flows expose protocol parameters to potential
attackers via URI query parameters (HTTP referrer), the browser
cache, or log file entries and could be replayed. In order to
reduce this threat, short-lived authorization codes are passed
instead of tokens and exchanged for tokens over a more secure
direct connection between client and authorization server.
It is much simpler to authenticate clients during the direct
request between client and authorization server than in the
context of the indirect authorization request. The latter would
require digital signatures.
Theoretically,
Access Tokens cannot tell us if the user has authenticated but auth code does.
Auth code should not be used to gain access to an API but access token should be.
If you have a single page application or mobile application with no or minimum backend, your application may want to access user's FB data directly at frontend. Hence the access token is provided.
In another case, you may want a user to register/login to your app using some external auth service provider like Facebook, Google etc. In this case, your frontend will send the auth code to the backend that can be used to get access token from Facebook at serverside. Now your server becomes enabled to access user's FB data from the server.
Basically, as an extension of Lix's answer, the access code route allows a Resource Owner (i.e. the Facebook User) to revoke authorization for their User Agent (i.e. their browser), e.g. by logging off, without revoking authorization for an offline Client (i.e. Your Application).
If this is not important, then there is no need to use the access code route.
Furthermore, the access code is provided to ensure that the Token provided to a server is actually registered to the Resource Owner (i.e. the Facebook User), and not the User Agent (or a Man-in-the-Middle).
This seems similar to the question of either choosing the implicit vs authorization code grant flow. In fact, here is what looks like an opposite view point?!.
Also, as Drew mentioned,
When the access token expires, attempts to use it will fail, and a new access token must be obtained via a refresh token.
another piece is the refresh token, but I don't see that being explained too well in the FB Docs. If I'm correct, the implicit grant (the direct token) should be really short lived, but that is to-be-enforced and FB.js seems to hide a lot of that (this one I have not looked as deep into).
If I'm correct, the code%20token is an optimization allowing both the User Agent to have a token and allowing for the server to initiate the token exchange process in a single request (as anything over Network IO is considered expensive, especially to a User Agent).
In OAuth 2.0 with facebook, the overall concept is simple as follows.
Step 1. Obtain "Authorization Code" by a GET request
request URI: https://www.facebook.com/dialog/oauth
Params:
response_type=code
client_id={add your "App id" got by registering app}
redirect_uri={add redirect uri defined at the registration of app}
scope={add the scope needed in your app}
Headers: None
Step 2. Obtain the "Access Token" by sending the authorization code as a POST request
URI: https://graph.facebook.com/oauth/access_token
Params:
grant_type=authorization_code
client_id=<add your "App id" got by registering app>
redirect_uri=<add redirect uri defined at the registration of app>
code=<obtained authorization code from previous step>
Headers:
Authorization:Basic encode <App Id:App Secret> with base64
Content-Type:application/json
Step 3. Use the access token got from above step and retrieve user resources
It’s because the access token is given to an AUTHENTICATED client (third-party app) using a shared secret that only FB and the client knows. The only way that the user could directly request the access token is by knowing the shared secret, which would make the secret public and could lead to a man-in-the-middle attack. Further, while FB can guarantee a secure connection to the user, FB can’t guarantee the handoff of the token to the client is secure. However, FB (and OAuth2) does require a secure connection between the client and FB. The access token is tied to the client public ID (usually hashed), which means only the original client application can use it to request the token because the secret is sent along with the authorization code to get the access token.
You recieve a token when the user logs in. But you might want to change the token when you are performing other actions. EG posting as your app/page or posting as a user with offline_access.