我有一个Spring/jhipster应用程序,带有一个按钮可以登录钥匙斗篷。当我单击登录按钮时,它会将我带到 keycloak,URL 看起来像
https://keycloak.mydomain.com/auth/realms/my-realm/protocol/openid-connect/auth?response_type=code&client_id=myclient&redirect_uri=http://localhost:8080/login/oauth2/code/oidc
所以在上面,我想更改<code>redirect_uri=http://localhost:8080/login/oauth2/code/oidc转换为其他内容。
所以我在 src/main/java/.. 中添加了以下代码。/config/AuthorizationServerConfig.java:
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("myclient")
.secret(passwordEncoder().encode("mysecret"))
.scopes("resource:read")
.authorizedGrantTypes("authorization_code")
.redirectUris("https://new-url-I-want.com");
}
}
但是即使有了上面的改变,redirect_uri根本没有改变。有人知道这是为什么吗?
以及有关我为什么进行这些更改的更多信息:
使用 OIDC 的授权代码流,服务提供商(在本例中为我的网站)为身份提供商(Keycloak)提供 URI,以便在身份验证成功后将用户重定向回。但是,根据 Spring 文档,“使用默认配置,虽然授权代码流在技术上是允许的,但它没有完全配置”:https://docs.spring.io/spring-security-oauth2-boot/docs/current/reference/html5/#oauth2-boot-authorization-server-authorization-code-grant
文档接着指出“OAuth2 Boot不支持将重定向URI配置为属性 — 比如,除了客户id和客户机密。“所以,
"若要添加重定向URI,您需要使用< code > InMemoryClientDetailsService 或< code > JdbcClientDetailsService 来指定客户端":https://docs . spring . io/spring-security-oauth 2-boot/docs/current/reference/html 5/# registering-a-redirect-uri-with-the-client
在方法SecurityConfigure. confiure
中添加以下行
.and()
.oauth2Login()
.defaultSuccessUrl("/url_to_redirect")
那是:
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { ...
@Override
public void configure(WebSecurity web) { ... }
@Override
public void configure(HttpSecurity http) throws Exception {
...
.and()
.authorizeRequests()
.antMatchers("/api/auth-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.oauth2Login()
.defaultSuccessUrl("/url_to_redirect") // <--- HERE
}
您可以通过添加以下属性和src/main/resources/config/application . yml来添加另一个重定向uri
security:
oauth2:
client:
provider:
oidc:
issuer-uri: http://localhost:9080/auth/realms/jhipster
registration:
oidc:
client-id: web_app
client-secret: web_app
redirect-uri: http://localhost:8080/my-custom-redirect
此外,您必须在SecurityConfiguration中为oauth2登录配置自定义重定向uri,如下所示
...
.and()
.oauth2Login()
.redirectionEndpoint()
.baseUri("/my-custom-redirect")
.and()
.and()
.oauth2ResourceServer()
...