In my team we are migrating our authentication solution to KeyCloak and we would like to maintain our current interface, not having to get redirected to the login page served by the KeyCloak server.
But we are having problems saving that data in the browser, we checked that the default login saves some data in the localStorage and in the cookies, but we could not find out how to make it work by hand. We do the following request to log our users in:
const data = new URLSearchParams();
data.append("grant_type", "password");
data.append("client_id", keycloakConfig.clientId);
data.append("username", username);
data.append("password", password);
const response = await fetch(
`${keycloakConfig.url}/realms/${keycloakConfig.realm}/protocol/openid-connect/token`,
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: data,
}
);
The request gives us status 200 and some tokens but it does not set any cookie.
Is there any resource were we can find how to do this by hand?
First of all, don’t implement an OIDC library; try to use an OIDC-certified one. But let’s say it’s just for local testing, you aren’t worried about OAuth Security Best Practices, and you like danger, like Tom Cruise :). Note that the ROPC (Resource Owner Password Grant) does not create a session on the IdP.
Lastly, ROPC will be deprecated in OAuth 2.1[1], so I recommend not using it.
[1] draft-ietf-oauth-v2-1-11 - The OAuth 2.1 Authorization Framework
1 Like
Hey! Thanks for the advice. My team and I are a little lost in this topic. We are using Keycloak-js to handle the authentication, but I couldn’t find any way to login in without redirecting to the keycloak interface. I suppose we should use an OIDC library like you said. Would that handle the authentication and create the session for us?
I would recommend following the standard OIDC [1]. This means that you (sdk/library) usually implement a redirection to the IdP, which follows one of the authentication flows.
There is a lot of theory behind the scenes about OIDC [1] and OAuth 2.0 [2] (plus OAuth Security Best Practices [2], etc.), but just to clarify your question: the IdP will create a session after the user is authenticated with one of the authentication mechanisms (the IdP cookie helps if you want SSO) and return the tokens to the app (I’m oversimplifying the idea).
Nevertheless, I usually say that this is how the standard works. If you want something different, you can do it, but be aware of all the potential drawbacks of reinventing the wheel
[1] Final: OpenID Connect Core 1.0 incorporating errata set 2
[2] RFC 6749 - The OAuth 2.0 Authorization Framework
[3] draft-ietf-oauth-security-topics-29