我试图在我的应用程序中使用Spring Security,但在每次成功注册后,在登录时遇到问题。 Spring将我重定向到failureUrl。我厌倦了寻找自己的错误。你能告诉我正确的方法吗?我真的很感激。有安全配置的代码:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private RegisterService registerService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(
"/registration",
"/js/**",
"/css/**",
"/img/**",
"/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(registerService).passwordEncoder(passwordEncoder());
}
}
服务对于注册和
负责@Service
public class RegisterService implements UserDetailsService {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserRepository userRepository;
public User save(UserDto userDto){
User user = new User();
user.setLogin(userDto.getLogin());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setEmail(userDto.getEmail());
user.setPassword(passwordEncoder.encode(userDto.getPassword()));
user.setRole("ROLE_USER");
return userRepository.save(user);
}
public User findByEmail(String email){
return userRepository.findByEmail(email);
}
public User findByLogin(String login){
return userRepository.findByLogin(login);
}
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
User user = userRepository.findByLogin(login);
if(user == null){
throw new UsernameNotFoundException("Invalid username or password.");
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(user.getRole()));
return new org.springframework.security.core.userdetails.User(
user.getLogin(), user.getPassword(), authorities);
}
}
答案 0 :(得分:0)
尝试在配置中添加defaultSuccessUrl
:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(
"/registration",
"/js/**",
"/css/**",
"/img/**",
"/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}
我还认为为permitAll()
调用formLogin
是多余的,因为这是默认设置,但这应该不是问题。