Location>code7788 >text

keycloak~Add dynamic kc recognized dynamic state for wechat QR code

Popularity:985 ℃/2024-07-29 10:26:25

This example will be keycloak community login through the realization of WeChat QR code login, and two micro-code is not keycloak dynamically generated, but through the WeChat provided by the js generated by the direct output on the page to achieve the way.

Dynamic state

When using the WeChat QR code login in Keycloak, the state parameter is indeed generated by the backend and is used to secure the login process against CSRF attacks, etc. If you try to write the state value dead or generate it on the front-end, it may lead to some security and integration issues, as the error you encountered in the parseSessionCode method.

Front-end code to generate keycloak's state

  • Format: session_code.tab_id.client_id
  • js method to generate state
<script src="${}/script/"></script>
<script>

var client_id = "${client_id!''}";
var redirect_uri = "${redirect_uri!''}";
if (redirect_uri.indexOf("?") > 0) {
    redirect_uri = redirect_uri + "&client_id=" + client_id;
} else {
    redirect_uri = redirect_uri + "?client_id=" + client_id;
}
let decodedLoginUrl = '${}'.replace(/&amp;/g, '&');
var stateValue = getQueryVariable(decodedLoginUrl, "session_code") + "." + getQueryVariable(decodedLoginUrl, "tab_id") + "." + getQueryVariable(decodedLoginUrl, "client_id")
new WxLogin({
    href: "/statics/css/",
    self_redirect: false,
    id: "wechatImg",
    appid: "${weixinAppId}",
    scope: "snsapi_login",
    redirect_uri: "${weixinCallback}?redirect_uri=" + redirect_uri,
    state: stateValue,
    style: "black",
    info: "${msg("weixinPrompt")}"
});

</script>
  • Once we've used the keycloak-recognized state above, we can set the callback address to the keycloak-generated callback address by default as well, and keycloak'sFirst Certification Streamcap (a poem)Post-Login FlowIt is also ready to use.