gpt4 book ai didi

java - Spring boot AuthenticationSuccessHandler 被忽略

转载 作者:行者123 更新时间:2023-11-30 10:08:51 24 4
gpt4 key购买 nike

你好 Stackoverflower,

我遇到了 Spring Security AuthenticationSuccessHandler 的问题。我实现了自定义 AuthenticationSuccessHandler,但当用户登录成功时它会被忽略。

我的自定义 AuthenticationSuccessHandler 类:

 @Component("customSuccessHandler")
public class CustomSuccessHandler implements AuthenticationSuccessHandler {



/* (non-Javadoc)
* @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {



System.out.println("***************************************************!!!!");
System.out.println("Logged Successful!!!!");
System.out.println("************************************!!!!");

//Ajout des informations utilisateur à la session
ajouterInformationsUtilisateurEnSession(request, authentication);



String urlDeRedirection = determinerUrlDeRedirection(authentication);

if (response.isCommitted()) {
System.out.println("La reponse a ete commitée, redirection vers : " + urlDeRedirection);
return;
}

response.sendRedirect(urlDeRedirection);

}

private String determinerUrlDeRedirection(Authentication auth) {

Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

List<String> roles = new ArrayList<>();

for (GrantedAuthority authority : authorities) {
System.out.println("ROLES : " + authority.getAuthority());

roles.add(authority.getAuthority());
}

if (roles.contains("ROLE_ADMIN")) {
return "/ajouterattributaire";
} else if (roles.contains("ROLE_DGA")) {
return "/home";
} else {
return "/error/403";
}

}

private void ajouterInformationsUtilisateurEnSession(HttpServletRequest request, Authentication authentication) {

//Récupération Session
HttpSession session = request.getSession();

//Définition des informations utilisateur à mettre en session : identifiant et roles

//Identifiant utilisateur
String identifiant = authentication.getName();

//Roles
List<String> roles = new ArrayList<>();

for (GrantedAuthority authority : authentication.getAuthorities()) {
roles.add(authority.getAuthority());
}

//Ajout des infomations utilisateur à la session
session.setAttribute("identifiant", identifiant);
session.setAttribute("roles", roles);
}}

我的配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

/*@Autowired
private DataSource dataSource;*/

private AccessDeniedHandler accessDeniedHandler;
private AuthenticationSuccessHandler authenticationSuccessHandler;
private AuthenticationFailureHandler authenticationFailureHandler;
private UserDetailsService userDetailsService;

@Autowired
public SecurityConfiguration(
@Qualifier("customAccessDeneiedHandler")AccessDeniedHandler accessDeniedHandler,
@Qualifier("customSuccessHandler")AuthenticationSuccessHandler authenticationSuccessHandler,
@Qualifier("customAuthenticationFailureHandler")AuthenticationFailureHandler authenticationFailureHandler,
@Qualifier("customUserDetailsService")UserDetailsService userDetailsService) {
this.accessDeniedHandler = accessDeniedHandler;
this.authenticationSuccessHandler = authenticationSuccessHandler;
this.authenticationFailureHandler = authenticationFailureHandler;
this.userDetailsService = userDetailsService;
}



/* (non-Javadoc)
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder)
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
//super.configure(auth);

auth.userDetailsService(userDetailsService) //auth.userDetailsService(utilisateurDetailsService)
.passwordEncoder(passwordEncoder());
}

//Authorization
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
//.antMatchers("/").permitAll()
.antMatchers("/ajouterattributaire").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
//.httpBasic()
.formLogin()
.loginPage("/login")
//.loginProcessingUrl("/login")
.usernameParameter("identifiant")
.passwordParameter("mot_de_passe")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout().permitAll();

http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}

/* (non-Javadoc)
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.WebSecurity)
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/images/**", "/var/signatures/**");
//web.ignoring().antMatchers("/static/**");
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}}

我的自定义 userDetailsS​​ervice :

@Service("customUserDetailsService")
public class UtilisateurDetailsService implements UserDetailsService {

@Autowired
private UtilisateurService utilisateurService;

@Autowired
private RoleService roleService;

/* (non-Javadoc)
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
*/
@Override
public UserDetails loadUserByUsername(String identifiantUtilisateur) throws UsernameNotFoundException {

Utilisateur utilisateur = utilisateurService.rechercherParIdentifiantUtilisateur(identifiantUtilisateur);

if (utilisateur == null) {
System.out.println("Problème d'authentification : " + new UsernameNotFoundException("Utilisateur Inexistant").getMessage());
throw new UsernameNotFoundException("Ulisateur inexistant dans la base de donnees!");

}
else {

List<String> nomRoles = roleService.determinerListeDesRolesDeLUtilisateur(utilisateur.getIdUtilisateur());

List<Role> roles = new ArrayList<>();

List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();

for (String nomRole : nomRoles) { //"ROLE_" +
simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + nomRole));
}

for (String nomRole : nomRoles) {
roles.add(roleService.rechercherRoleParNomRole(nomRole));
}

//Affectation role à l'utilisateur
utilisateur.setRoles(roles);

System.out.println("*********************************************************************************");

System.out.println("Id utilisateur : " + utilisateur.getIdUtilisateur());
System.out.println("Identifiant : " + utilisateur.getIdentifiantUtilisateur());
System.out.println("Nom : " + utilisateur.getNomUtilisateur());
System.out.println("Mot de passe : " + utilisateur.getMotDePasseUtilisateur());
System.out.println("Est actif : " + utilisateur.getEstActifUtilisateur());
System.out.println("Signature utilisateur : " + utilisateur.getSignatureUtilisateur());
System.out.println("Date création : " + utilisateur.getDateHeureCreationUtilisateur());
System.out.println("Authoritises : " + utilisateur.getAuthorities());

System.out.println("Roles : " + utilisateur.getRoles().isEmpty());

System.out.println("Taille roles : " + utilisateur.getRoles().size());
System.out.println("Roles : " + utilisateur.getRoles().isEmpty());

for(Role role : utilisateur.getRoles()) {
System.out.println("Role : " + role.getAuthority());
}
System.out.println("*********************************************************************************");

//return utilisateur;
/*User user = new User(utilisateur.getIdentifiantUtilisateur(),
utilisateur.getMotDePasseUtilisateur(),
simpleGrantedAuthorities);*/

//return user;
return utilisateur;
}

}}

我不知道怎么回事。我觉得校长没问题。

最佳答案

您的 CustomSuccessHandler 被安全配置中的默认处理程序覆盖。

只需从 SecurityConfiguration 类中删除以下行:.defaultSuccessUrl("/")

关于java - Spring boot AuthenticationSuccessHandler 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53601653/

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