keycloak redirect_uri is incorrect
By:Roy.LiuLast updated:2023-12-15
在用keycloak做单点登录集成的时候,在本地测试没问题,在UAT环境有时候,发现keycloak发起的redirect_uri 不正确,比如原来是域名的,有可能变成了IP,其实是可以自己指定的。自己指定redirect_uri 是自己配置。代码如下:
import org.keycloak.adapters.AdapterTokenStore; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.OAuthRequestAuthenticator; import org.keycloak.adapters.RequestAuthenticator; import org.keycloak.adapters.spi.HttpFacade; import org.keycloak.adapters.springsecurity.authentication.SpringSecurityRequestAuthenticator; import org.keycloak.adapters.springsecurity.authentication.SpringSecurityRequestAuthenticatorFactory; import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; @Component public class KeycloackAuthenticationProcessingFilterPostProcessor implements BeanPostProcessor { @Value("${customize.keycloak.redirect-uri}") private String redirectUri; private static final Logger logger = LoggerFactory.getLogger(KeycloackAuthenticationProcessingFilterPostProcessor.class); private void process(KeycloakAuthenticationProcessingFilter filter) { filter.setRequestAuthenticatorFactory(new SpringSecurityRequestAuthenticatorFactory() { @Override public RequestAuthenticator createRequestAuthenticator(HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort) { return new SpringSecurityRequestAuthenticator(facade, request, deployment, tokenStore, sslRedirectPort) { @Override protected OAuthRequestAuthenticator createOAuthAuthenticator() { return new OAuthRequestAuthenticator(this, facade, deployment, sslRedirectPort, tokenStore) { @Override protected String getRequestUrl() { logger.info("get redirect uri: {}", redirectUri); return redirectUri; } }; } }; } }); } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof KeycloakAuthenticationProcessingFilter) { logger.info("Injecting Custom handler..."); process(((KeycloakAuthenticationProcessingFilter) bean)); } return bean; } }
可以在配置文件中增加一个
customize.keycloak.redirect-uri= http://www.mydomain.com/sso/login
用这种方式就能实现自定义redirect_uri 了。
From:一号门
Previous:出差石家庄,去正定县古镇转了一圈
COMMENTS