Spring Boot安全性:授权后仍保留在登录表单上,不会发生错误。

huangapple go评论54阅读模式
英文:

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:
Spring Boot安全性:授权后仍保留在登录表单上,不会发生错误。
Spring Boot安全性:授权后仍保留在登录表单上,不会发生错误。
Spring Boot安全性:授权后仍保留在登录表单上,不会发生错误。

英文:

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>

My DEBUG logs.
Spring Boot安全性:授权后仍保留在登录表单上,不会发生错误。
Spring Boot安全性:授权后仍保留在登录表单上,不会发生错误。
Spring Boot安全性:授权后仍保留在登录表单上,不会发生错误。

答案1

得分: 0

  1. 在我的情况下,错误是定义了sessionCreationPolicy(SessionCreationPolicy.STATELESS); 我移除了这部分。
  2. 在我的程序中,我为成功认证后的重定向制作了自己的组件,但我忘记在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/");
        }
    }
}
英文:
  1. In my case, the mistake was to define sessionCreationPolicy(SessionCreationPolicy.STATELESS); I removed this side.
  2. 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(&quot;/acthasform/&quot;).permitAll().anyRequest().authenticated();
http.authenticationProvider(authenticationProvider());
http.formLogin().loginPage(&quot;/login&quot;).permitAll().successHandler(successHandler).usernameParameter(&quot;username&quot;).passwordParameter(&quot;password&quot;).permitAll().and()
.logout().permitAll().and().exceptionHandling().accessDeniedPage(&quot;/403&quot;);

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/");
}
}
}

huangapple
  • 本文由 发表于 2023年4月19日 17:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定