gpt4 book ai didi

spring - Spring MVC Java 中的 AuthenticationSuccessHandler 基于 Java 的配置

转载 作者:行者123 更新时间:2023-12-02 03:30:58 24 4
gpt4 key购买 nike

我有三个角色,我想在登录后根据用户的角色将用户重定向到不同的页面。我知道这可以通过 AuthenticationSuccessHandler 来完成,但我在基于 Java 的配置中声明它时遇到了麻烦。

到目前为止我已经做到了。

protected void configure(HttpSecurity http) throws Exception {

http
.authorizeRequests()
.antMatchers("/resources/**", "/login").permitAll()
.antMatchers("/admin/**").hasRole("USER")
.and()

.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.successHandler(successHandler) //----- to handle user role
.failureUrl("/loginfailed")
.permitAll()
.and()

.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.deleteCookies("JSESSIONID")
.invalidateHttpSession( true )
.and();
}

我的问题是在哪里声明 successHandler 以及如何在此类中 Autowiring 它,或者如何在此类中声明 successHandler 方法并使用它。

最佳答案

试试这个:Moving Spring Security To Java Config, where does authentication-success-handler-ref go?

上面帖子中的代码:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("")
.defaultSuccessUrl("/")
.failureUrl("")
.successHandler(//declare your bean here)
.and()
.logout()
.permitAll()
.and()
}

然后在身份验证处理程序中,您可以应用所需的逻辑

public class MYSuccessHandler implements    AuthenticationSuccessHandler {


private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);

}

protected void handle(HttpServletRequest request,
// logic

redirectStrategy.sendRedirect(request, response, targetUrl);
}

/** Builds the target URL according to the logic defined in the main class Javadoc. */
protected String determineTargetUrl(Authentication authentication) {
}
}

此处列出了教程 http://www.baeldung.com/spring_redirect_after_login

关于spring - Spring MVC Java 中的 AuthenticationSuccessHandler 基于 Java 的配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28923281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com