我正在学习 Spring Security 创建简单的登录表单。我正在使用java配置。我有内存用户和一个简单的过滤器链。
但是当我输入现有的用户名和密码组合时Spring将我重定向回登录表单,网址为:login?error .
这是我的Spring Security配置类:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// @Autowired
// AuthProvider provider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("").roles("USER")
.and()
.withUser("user2").password("").roles("USER")
.and()
.withUser("admin").password("1").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.authenticationProvider(provider);
// }
}
这是我的 JSP 表单:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
${message}
<br>
<form method="post" action="/login">
<input type="text" name="login"/>
<input type="text" name="pass"/>
<input type="submit" value="enter"/>
</form>
</body>
</html>
最佳答案
在你的代码中
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("").roles("USER")
.and()
.withUser("user2").password("").roles("USER")
.and()
.withUser("admin").password("1").roles("ADMIN");
}
将@Autowired
替换为@Override
并按照此处的做法 [1]:https://www.baeldung.com/spring-security-login
... auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER")
.and() ...
使用BCryptPasswordEncoder
作为相同代码中的bean
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
关于java - Spring Security/Java 配置 - 无法使用现有用户登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201510/