Spring Boot 3.2.4 和 Spring Security 6.2.3
我已使用如下配置在应用程序中启用了 OAuth2 和表单登录:
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {
private final MyUserService userService;
private final PasswordEncoder encoder;
@Bean
DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userService);
authProvider.setPasswordEncoder(encoder);
return authProvider;
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http, MyOAuth2UserService oauth2Service) throws Exception {
http
.authorizeHttpRequests(this::configureAuthorization)
.oauth2Login(c -> configureOAuth2(c, oauth2Service))
.formLogin(this::configureFormLogin)
.httpBasic(Customizer.withDefaults()) // Used for APIs when called other than from the UI
.logout(this::configureLogout)
;
return http.build();
}
private void configureAuthorization(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry authorize) {
authorize
.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ERROR).permitAll()
.requestMatchers("/*/*.js", "/*/*/*.js", "/css/**", "/lib/**", "/assets/**", "favicon.ico").permitAll()
.requestMatchers("/", "/login", "/logout").permitAll()
.requestMatchers("/restrictedStuff/**").hasAnyRole("GOOD_GUY")
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();
}
private void configureOAuth2(OAuth2LoginConfigurer<HttpSecurity> oauthLogin, MyOAuth2UserService userService) {
oauthLogin
.userInfoEndpoint(endpoint -> endpoint.oidcUserService(userService))
//.loginPage("/login")
;
}
private void configureFormLogin(FormLoginConfigurer<HttpSecurity> formLogin) {
formLogin
//.loginPage("/login")
.permitAll();
}
private void configureLogout(LogoutConfigurer<HttpSecurity> logout) {
logout
.logoutSuccessUrl(LOGIN_PAGE)
.permitAll();
}
}
这按预期工作,
/login
页面自动生成,同时包含用户/密码表单和,为我的 OIDC 提供商(Google)提供“使用 OAuth 2.0 登录”链接。
现在我需要为表单和 OAuth2 链接使用自定义登录页面。这就是我无法工作的原因。
在上面的代码片段中,我注释掉了对
loginPage("/login")
的调用;我尝试取消注释其中一个或两个(以及 MVC 控制器中的标准“/login”端点),但这会产生奇怪/损坏的结果。
在此身份验证设置中使用自定义登录页面的正确方法是什么?
Google 提供自定义登录页面。当您设置 OpenID Connect 时,注册您想要用于应用程序 oath2 登录的 uri,并使用该 uri 作为按钮的链接。这是来自 Google 的指令:https://developers.google.com/identity/openid-connect/openid-connect#java_1
示例按钮:
<div class="google-login-btn mt-3">
<a href="/oauth2/authorization/google" style="color: #2552e7">
Login with Google
</a>
</div>