java - Spring Security/Java 配置 - 无法使用现有用户登录

标签 java spring spring-security

我正在学习 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/

相关文章:

java - 将参数id传递到另一个页面

java - 使用 spring 表单在 spring mvc 中上传文件不起作用

使用接口(interface)的 Java 泛型方法

java - 在字符串中放入逗号

java - Android Firebase 数据库检查用户是否属于特定组

java - 如何使用 spring security 使用空密码进行基本身份验证?

java - 在最新的 spring-security-oauth2-2.0.6.RELEASE.jar 中找不到 TokenServicesUserApprovalHandler

java - 使用JDK 10时找不到javax.annotation.Resource的lookup()方法

javascript - Google Charts - 从 Ajax 创建数据

java - Spring MVC、Spring 安全 : Unable to load login template