【问题标题】:How can i use spring security to authenticate users with an Id and password instead of username and password如何使用 Spring Security 使用 ID 和密码而不是用户名和密码对用户进行身份验证
【发布时间】:2020-01-18 09:20:18
【问题描述】:

我是 Spring Security 的新手,想对拥有 userId 和密码的用户进行身份验证。 userId 在注册时提供给用户。

第二个问题是用户名和密码在不同的表中。 那么,如何自定义 Spring Security 以满足这两个要求。

这是我的安全配置类。 我正在使用弹簧靴 2

公共类 SecurityConfig 扩展 WebSecurityConfigurerAdapter {

@Autowired
private DbConfig dbConfig;

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers("/static/**")
        .antMatchers(HttpMethod.GET, "/public/**")
        .antMatchers(HttpMethod.GET, "/index.html");
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.jdbcAuthentication()
        .dataSource(dbConfig.dataSource())
        .usersByUsernameQuery("select username,password,active from user where username=?")
        .authoritiesByUsernameQuery("select username,authority from authorities where username=?")
        .passwordEncoder(passwordEncoder());
}

 private PasswordEncoder passwordEncoder() {

    return new BCryptPasswordEncoder();
}

@Override
 protected void configure(HttpSecurity http) throws Exception {
     http
        .authorizeRequests()
        .antMatchers("/login")
        .permitAll()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/dashboard")
        .and()
        .csrf()
        .disable();
 }

}

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-security


    【解决方案1】:

    您需要使用自己的UserDetailsService

    public MyUserDetailsService implements UserDetailsService {
    
        @Override
        public User loadUserByUsername(String username) {
            // write the query yourself
        }
    }
    

    然后在你的配置中:

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        return new MyUserDetailsService();
    }
    

    您可以在the section of the Spring Security Reference 中找到更多关于您的问题的详细信息。

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2014-03-08
      • 2021-12-14
      相关资源
      最近更新 更多