8

Spring Boot Web アプリケーションを開発しています。問題はログイン シナリオにあります。ユーザー名「Ali」で登録されたユーザーがいるとします。このユーザーは、ユーザー名「Ali」または「ali」でログインできます。以下のコードは、私の春のセキュリティ構成クラスを表しています。比較してみると、Spring Boot は大文字小文字の因数をチェックしていないようですが、チェックしてほしいです。

パッケージ nf.something.conf;

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

javax.sql.DataSource をインポートします。

/**
 ※2016/11/12 レザ作成。
 */
@構成
public class SecurityConf は WebSecurityConfigurerAdapter を拡張します {

    @Autowired
    プライベート DataSource データソース。
    @Autowired
    プライベート EventRepository eventRepository;

    // HttpSessionEventPublisher を登録する
    @豆
    public static ServletListenerRegistrationBean httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean(new HttpSessionEventPublisher());
    }

    @オーバーライド
    protected void configure(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\""));
    }

    @豆
    public SessionRegistry sessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        sessionRegistry を返します。
    }

    @豆
    public WebMvcConfigurer corsConfigurer() {
        新しい WebMvcConfigurerAdapter() を返します {
            @オーバーライド
            public void addCorsMappings(CorsRegistry レジストリ) {
                registry.addMapping("/**").allowedOrigins("*").allowedMethods("PUT", "POST", "GET", "DELETE", "HEAD");
            }
        };
    }

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsS​​ervice userDetailsS​​ervice) throws Exception {
        /*認証
                .jdbcAuthentication().usersByUsernameQuery("ユーザー名=?のユーザーから、ユーザー名、パスワード、有効として「true」を選択します。")
                .authoritiesByUsernameQuery("username=? の機関からユーザー名、機関を選択")
                .dataSource(データソース).passwordEncoder(新しいBCryptPasswordEncoder());*/
        auth.userDetailsS​​ervice(userDetailsS​​ervice)
                .passwordEncoder(新しい BCryptPasswordEncoder());
    }

    @豆
    public AuthenticationEntryPoint restAuthenticationEntryPoint() {
        新しい RestAuthenticationEntryPoint() を返します。
    }

    @豆
    public AuthenticationFailureHandler restAuthenticationFailureHandler() {
        新しい SimpleUrlAuthenticationFailureHandler() を返します。
    }

    @豆
    public AuthenticationSuccessHandler restAuthenticationSuccessHandler() {
        新しい RESTAuthenticationSuccessHandler(eventRepository) を返します。
    }

    @豆
    public LogoutSuccessHandler restLogoutSuccessHandler() {
        新しい RESTLogoutSuccessHandler(eventRepository) を返します。
    }
}

クラスequalsにメソッドも実装しました:User

@オーバーライド
    public boolean equals(Object o) {
        if (this == o) は true を返します。
        if (!(o instanceof User)) は false を返します。

        ユーザー ユーザー = (ユーザー) o;
     
        if (!getUsername().equals(user.getUsername())) return false;
        if (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)
            false を返します。
        return getMobilePhone() != null ? getMobilePhone().equals(user.getMobilePhone()) : user.getMobilePhone() == null;
    }
4

2 に答える 2