英文:
Spring Boot Security After authorization, it remains on the login form, it does not issue errors
问题
I've translated the non-code portions of your text as requested:
"Why is it that when I enter my username and password and click the button, the page just reloads, does not give any errors, what am I doing wrong?"
Debug logs:
英文:
Why is it that when I enter my username and password and click the button, the page just reloads, does not give any errors, what am I doing wrong?
code
@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("u").passwordParameter("p")
.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);
}
}
public class MyUserDetails implements UserDetails{
private User user;
public MyUserDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<Role> roles = user.getRoles();
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for(Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return user.isEnabled();
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Login - Spring Security Example</title>
<style type="text/css">
body div {
text-align: center;
}
label, input[type=text], input[type=password] {
display: inline-block;
width: 150px;
margin: 5px;
}
input[type=submit] {
width: 60px;
margin: 10px;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<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="u" /></div>
<div><label>Password: </label><input type="password" name="p" /></div>
<div><input type="submit" value="Login" /></div>
</form>
</div>
</div>
</body>
</html>
答案1
得分: 0
- 在我的情况下,错误是定义了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<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ROLE_ADMIN")) {
response.sendRedirect("/regulatoryform/");
} else {
response.sendRedirect("/regulatoryact/");
}
}
}
英文:
- In my case, the mistake was to define sessionCreationPolicy(SessionCreationPolicy.STATELESS); I removed this side.
- In my program, I made my own component for redirection after successful authentication, but I forgot to use it in WebSecurityConfig.
Correct code
@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<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ROLE_ADMIN")) {
response.sendRedirect("/regulatoryform/");
}
else {
response.sendRedirect("/regulatoryact/");
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论