[英]Spring Security custom login authentication not working
我正在尝试实现 spring 安全自定义登录。 当它在标准 spring 表单上运行时,它可以很好地登录和验证用户。 但是现在我将其更改为自定义登录页面,它不再起作用了。 下面是代码。 当我输入用户名和密码并单击提交时,它停留在登录页面而不验证用户身份。 代码有什么问题?
@SpringBootApplication
@EntityScan(basePackages="projetos.model")
@ComponentScan(basePackages= {"projetos.*"})
@EnableJpaRepositories(basePackages= {"projetos.repository"})
@EnableTransactionManagement
@EnableWebMvc
public class PessoaApplication implements WebMvcConfigurer{
public static void main(String[] args) {
SpringApplication.run(PessoaApplication.class, args);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("/login");
registry.setOrder(Ordered.LOWEST_PRECEDENCE);
}
}
@Service
@Transactional
public class ImplementacaoUserDetailsService implements UserDetailsService{
@Autowired
private UsuarioRepository usuarioRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Usuario usuario = usuarioRepository.selectUsuarioPorLogin(username);
if (usuario == null) {
throw new UsernameNotFoundException("Usuario não foi encontrado.");
}
return new User(usuario.getLogin(), usuario.getSenha(),
usuario.isEnabled(), true,
true, true,
usuario.getAuthorities());
}
}
@Configuration
@EnableWebSecurity
public class WebConfigSecurity extends WebSecurityConfigurerAdapter{
@Autowired
private ImplementacaoUserDetailsService implementacaoUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/gerente/**").hasAnyRole("GERENTE", "ADMIN")
.antMatchers(HttpMethod.GET, "/diretor/**").hasAnyRole("DIRETOR", "ADMIN")
.antMatchers(HttpMethod.GET, "/").permitAll()
.anyRequest().authenticated()
.and().formLogin().permitAll()
.loginPage("/login")
//.defaultSuccessUrl("")
.failureUrl("/login?error=true")
.and().logout().logoutSuccessUrl("/login")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(implementacaoUserDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
您需要将loginProcessingUrl()
添加到您的配置中。
loginPage("...")
指示 Spring Security 需要身份验证时,将浏览器重定向到该 URL
loginProcessingUrl("...")
是提交用户名和密码的 URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.