@NatashaBal

Почему при нажатии на кнопку отправить, логин форма просто обновляется(spring boot security)?

нажатии на кнопку отправить, логин форма просто обновляется вместо того, что бы перейти на указанную в defaultSuccessUrl страницу, ошибок никаких не выдает, возможно не происходит авторизация?но мне не понятно почему.
вот мой код
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
	@Bean
	public AuthenticationSuccessHandler successHandler() {
	    SimpleUrlAuthenticationSuccessHandler handler = new SimpleUrlAuthenticationSuccessHandler();
	    handler.setUseReferer(true);
	    return handler;
	}
	@Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }
     
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
    	BCryptPasswordEncoder bc=new BCryptPasswordEncoder();
        return bc;
    }
   
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
      return authConfig.getAuthenticationManager();
    }
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }
  
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	http.sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);;
    http.authorizeHttpRequests().requestMatchers("/acthasform/").permitAll()
    .anyRequest().authenticated()
   .and()
   .formLogin().loginPage("/login") .successHandler(successHandler())      
   .usernameParameter("username").passwordParameter("password")            
   .permitAll().defaultSuccessUrl("/regulatoryform/")
   .and()
.logout().permitAll().and().
    exceptionHandling().accessDeniedPage("/403")
    ;
    return http.build();
}
}


@Component
public class Securityhandler implements AuthenticationSuccessHandler{
	   @Override
	   public void onAuthenticationSuccess(HttpServletRequest request,   HttpServletResponse response, Authentication authentication) throws IOException  {
	        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
	        if (roles.contains("ROLE_ADMIN")) {
	            response.sendRedirect("/regulatoryform/list.html");
	        }
	    }
}


public class UserDetailsServiceImpl implements UserDetailsService{
	
    @Autowired
	private UserRepository userRepository;
    
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user=userRepository.getUserByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException("Could not find user");
		}
		return new MyUserDetails(user);	
	}
}

@Controller
  public class LoginController {
 
  @GetMapping("/login") public String login() {
  System.out.println("логин форма"); 
  return "login.html"; } 

}



Логин форма

<div>
    <div>
        <h2>Spring Security Login Form</h2>
    </div>
    <div th:if="${param.error}">
        <h3>Invalid username and password.</h3>
    </div>
    <div th:if="${param.logout}">
        <h3>You have been logged out.</h3>
    </div>
    <div>
    <form th:action="@{/login}" method="post">
        <div><label>Username: </label> <input type="text" name="username" /></div>
        <div><label>Password: </label><input type="password" name="password" /></div>
       <div class="auth__buttons" style="">
						<button class="btn" style="width: 150px; height: 35px">Enter</button>
					</div>
    </form>
    </div>
</div>
  • Вопрос задан
  • 112 просмотров
Пригласить эксперта
Ответы на вопрос 1
@NatashaBal Автор вопроса
В моем случае ошибкой было определение sessionCreationPolicy(SessionCreationPolicy.STATELESS); Я удалила эту строку.
В своей программе я создала свой собственный компонент для перенаправления после успешной аутентификации, но я забыла использовать его в WebSecurityConfig.
Правильный код

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Autowired
Securityhandler successHandler;

@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl();
}

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

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}

@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests().requestMatchers("/acthasform/").permitAll().anyRequest().authenticated();
http.authenticationProvider(authenticationProvider());
http.formLogin().loginPage("/login").permitAll().successHandler(successHandler).usernameParameter("username")
.passwordParameter("password").permitAll().and().logout()
.permitAll().and().exceptionHandling().accessDeniedPage("/403");

return http.build();


}
}

@Component
public class Securityhandler implements AuthenticationSuccessHandler{


@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
Set roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ROLE_ADMIN")) {
response.sendRedirect("/regulatoryform/");
}
else {
response.sendRedirect("/regulatoryact/");
}
}
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы