8

我正在开发一个 Spring Boot Web 应用程序。问题出在登录场景中。假设我有一个用户名“Ali”注册的用户。该用户可以使用用户名“Ali”或“ali”登录。下面的代码代表我的 spring 安全配置类。似乎在比较时,Spring boot 不检查大写小写因素,但我希望它被检查。

包 nf.something.conf;

导入 nf.something.repo.EventRepository;
导入 org.springframework.beans.factory.annotation.Autowired;
导入 org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
导入 org.springframework.context.annotation.Bean;
导入 org.springframework.context.annotation.Configuration;
导入 org.springframework.http.HttpMethod;
导入 org.springframework.security.authentication.AuthenticationProvider;
导入 org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
导入 org.springframework.security.config.annotation.web.builders.HttpSecurity;
导入 org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
导入 org.springframework.security.core.Authentication;
导入 org.springframework.security.core.AuthenticationException;
导入 org.springframework.security.core.session.SessionRegistry;
导入 org.springframework.security.core.session.SessionRegistryImpl;
导入 org.springframework.security.core.userdetails.UserDetailsS​​ervice;
导入 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
导入 org.springframework.security.web.AuthenticationEntryPoint;
导入 org.springframework.security.web.authentication.AuthenticationFailureHandler;
导入 org.springframework.security.web.authentication.AuthenticationSuccessHandler;
导入 org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
导入 org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
导入 org.springframework.security.web.header.writers.StaticHeadersWriter;
导入 org.springframework.security.web.session.HttpSessionEventPublisher;
导入 org.springframework.web.servlet.config.annotation.CorsRegistry;
导入 org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
导入 org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

导入 javax.sql.DataSource;

/**
 * 由 reza 于 2016 年 11 月 12 日创建。
 */
@配置
公共类 SecurityConf 扩展 WebSecurityConfigurerAdapter {

    @自动连线
    私有 DataSource 数据源;
    @自动连线
    私有事件存储库事件存储库;

    // 注册 HttpSessionEventPublisher
    @豆
    公共静态 ServletListenerRegistrationBean httpSessionEventPublisher() {
        返回新的 ServletListenerRegistrationBean(new HttpSessionEventPublisher());
    }

    @覆盖
    受保护的无效配置(HttpSecurity http)抛出异常{
        http.authorizeRequests()
// .antMatchers(HttpMethod.POST, "/users/").permitAll()
                .antMatchers(HttpMethod.GET, "/**").permitAll()
                .antMatchers(HttpMethod.POST, "/**").permitAll()
                .antMatchers(HttpMethod.PUT, "/**").permitAll()
                .antMatchers(HttpMethod.DELETE, "/**").permitAll()
                .antMatchers("/swagger*").permitAll()
                //.anyRequest().permitAll()
                //.and().csrf().disable();
                .anyRequest().authenticated()
                .and().httpBasic()
                .and().formLogin().successHandler(restAuthenticationSuccessHandler()).failureHandler(restAuthenticationFailureHandler())
                .and().logout().logoutSuccessHandler(restLogoutSuccessHandler())
                .and().exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint())
                .and().csrf().disable().cors() //TODO 当我们准备好时启用csrf
                .and().sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true).sessionRegistry(sessionRegistry());
        http.headers().cacheControl().disable()
                .addHeaderWriter(new StaticHeadersWriter("WWW-Authenticate","xBasic realm=\"fake\""));
    }

    @豆
    公共 SessionRegistry sessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        返回会话注册表;
    }

    @豆
    公共 WebMvcConfigurer corsConfigurer() {
        返回新的 WebMvcConfigurerAdapter() {
            @覆盖
            公共无效 addCorsMappings(CorsRegistry 注册表){
                registry.addMapping("/**").allowedOrigins("*").allowedMethods("PUT", "POST", "GET", "DELETE", "HEAD");
            }
        };
    }

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @自动连线
    public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsS​​ervice userDetailsS​​ervice) 抛出异常 {
        /*认证
                .jdbcAuthentication().usersByUsernameQuery("Select username,password, 'true' as enabled from Users where username=?")
                .authoritiesByUsernameQuery("select username, authority from authority where username=?")
                .dataSource(datasource).passwordEncoder(new BCryptPasswordEncoder());*/
        auth.userDetailsS​​ervice(userDetailsS​​ervice)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @豆
    公共 AuthenticationEntryPoint restAuthenticationEntryPoint() {
        返回新的 RestAuthenticationEntryPoint();
    }

    @豆
    公共 AuthenticationFailureHandler restAuthenticationFailureHandler() {
        返回新的 SimpleUrlAuthenticationFailureHandler();
    }

    @豆
    公共 AuthenticationSuccessHandler restAuthenticationSuccessHandler() {
        返回新的 RESTAuthenticationSuccessHandler(eventRepository);
    }

    @豆
    公共 LogoutSuccessHandler restLogoutSuccessHandler() {
        返回新的 RESTLogoutSuccessHandler(eventRepository);
    }
}

我还在课堂上实现equals了方法User

@覆盖
    公共布尔等于(对象o){
        if (this == o) 返回真;
        if (!(o instanceof User)) 返回假;

        用户用户=(用户)o;
     
        如果 (!getUsername().equals(user.getUsername())) 返回 false;
        如果 (getName() != null ? !getName().equals(user.getName()) : user.getName() != null) 返回 false;
        if (getFamily() != null ? !getFamily().equals(user.getFamily()) : user.getFamily() != null) 返回 false;
        if (getPassword() != null ? !getPassword().equals(user.getPassword()) : user.getPassword() != null)
            返回假;
        返回 getMobilePhone() != null ?getMobilePhone().equals(user.getMobilePhone()) : user.getMobilePhone() == null;
    }
4

2 回答 2

4

您能否尝试更改用户名列:

ALTER TABLE USERS MODIFY username VARCHAR(50) BINARY 
于 2017-06-29T12:49:55.320 回答
2

正如@dur 在评论中所说,我在我的数据库中检查了这些查询:

Select username, password, 'true' as enabled 
from Users 
where username = 'Ali'

Select username, password, 'true' as enabled 
from Users 
where username = 'ali'

他们都返回了相同的结果。所以我改变了username我的表排序规则的列user如下(以前的排序规则是utf8_general_ci):

SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `mydb`.`user`
  CHANGE `username` `username` VARCHAR(50) CHARSET utf8 COLLATE utf8_bin NOT NULL;
SET FOREIGN_KEY_CHECKS=1;

现在username将检查列是否区分大小写。

于 2017-06-29T11:41:33.380 回答