java Spring引导问题使用AuthenticationSuccessHandler重定向到外部URL
我第一次使用SpringBoot为REACT web应用程序设置用户登录系统。目前,我正在尝试在成功验证后将用户重定向到REACT应用程序中的另一个页面。我正在使用自定义AuthenticationSuccessHandler来处理实际的重定向
@Override
protected void configure(HttpSecurity http) throws Exception {
CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManagerBean());
customAuthenticationFilter.setFilterProcessesUrl("/api/v*/login/**");
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().antMatchers("/api/v*/login/**").permitAll();
http.authorizeRequests().antMatchers(HttpMethod.GET, "api/v*/users/**").hasAnyAuthority("PRODUCER");
http.authorizeRequests().antMatchers("/api/v*/registration/**").permitAll();
http.authorizeRequests().anyRequest().authenticated();
http.formLogin().loginPage("http://localhost:3000/login").successHandler(myAuthenticationSuccessHandler());
@Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
return new RedirectLoginSuccessHandler();
}
public class RedirectLoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException {
httpServletResponse.sendRedirect("http://localhost:3000");
}
}
API在端口8080上运行,react登录表单在端口3000/login上运行,身份验证是通过向localhost:8080/API/v1/login发送POST请求来完成的(返回一个JWT访问令牌),尝试之后,我希望用户重定向到localhost:3000的主页,但是重定向被忽略,除非我使用从Spring获得的登录表单和loginForm()方法
我还尝试将重定向与JWT令牌一起发送,作为对api/v1/login的POST请求的响应,但CORS在这样做时遇到了问题。我做错了什么?我看到的关于成功身份验证后重定向的教程涉及html文件,如home。html重定向,我假设他们能够通过将REACT和Spring boot项目捆绑到一个mono存储库中来实现这一点
# 1 楼答案
也许试试这样的
# 2 楼答案
通过
formLogin
,Spring Security基本上为您提供了以下步骤(简化):AuthenticationEntryPoint
会将您重定向到formLogin().loginPage("http://localhost:3000/login")
李>username
和password
之后,您需要将它们发布到formLogin().loginProcessingUrl("/login123")
(如果您没有指定,则默认值应为“/login”)李>"/login123"
上匹配器的UsernamePasswordAuthenticationFilter
将拦截您的帖子,并使用username
和password
验证您的用户李>.successHandler(myAuthenticationSuccessHandler())
来完成其工作李>在这里,因为
您没有遵循步骤2的流程(您没有将用户名/密码发布到“/login123”),之后就无法获得Spring Security支持的功能(例如
this.rememberMeServices.loginSuccess
,this.successHandler.onAuthenticationSuccess
,…)对于您的案例,在您从
a POST-request to localhost:8080/api/v1/login
获得JWT后,您可以自己重定向,您不需要依赖.successHandler(myAuthenticationSuccessHandler())