Spring securityカスタムパスワード検証(一)

4875 ワード

何日間もやりましたが、大体まとめます.私が見つけたカスタムパスワードの検証には2つの方法があります.インターネットの書き込みによって、確かにパスワードの検証ができます.しかし、パスワードが一致しなくて、BadCredentials Exceptionを抛り出しました.ユーザーがアクセス権ページに入るのを止めることができません.Spring Securityが投げたBadCredentials Exceptionに対して処理していないような気がします.反応がないです.最後にDisplantials Exceptionを抛り出しました.Spring Securityは正常に反応し、指定されたパスワードエラーアドレスに正常にリダイレクトします.
本論文ではまず第一種類を紹介します.Authentication Providerを実現するか、あるいはAuthentication Providerを実現するか、DaoAuthentication Providerなどが可能です.
Spring Security主な配置類
/**
 * Created by fjc on 2018-04-17.
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;



    @Bean
    public AuthenticationProvider authenticationProvider() {
        AuthenticationProvider authenticationProvider = new MyAuthenticationProvider();
        return authenticationProvider;
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/welcome**").permitAll()
                .antMatchers("/user/save").permitAll()
                .antMatchers("/user/admin**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/user/dba**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
                .and().formLogin().loginPage("/user/login").failureUrl("/user/login?error").successHandler(customSuccessHandler)
                .usernameParameter("ssoId").passwordParameter("password")
                .and().csrf()
                .and().exceptionHandling().accessDeniedPage("/user/login?access");
    }

}
UserDetails Service実現類:
/**
 * Created by fjc on 2018/4/22.
 */
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserProfileMapper userProfileMapper;

    public UserDetails loadUserByUsername(String ssoId) throws UsernameNotFoundException {
        User user = userMapper.findBySso(ssoId);
        System.out.println("User : "+user);
        if(user==null){
            System.out.println("User not found");
            throw new UsernameNotFoundException("Username not found");
        }
        return new org.springframework.security.core.userdetails.User(user.getSso_id(), user.getPassword(),
                user.getState().equals("Active"), true, true, true, getGrantedAuthorities(user.getId()));
    }

    private List getGrantedAuthorities(int userid){
        List authorities = new ArrayList();

        List list = userProfileMapper.findUserProfileByUserid(userid);

        for(UserProfile userProfile : list){
            System.out.println("UserProfile : "+userProfile);
            authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));
        }
        System.out.print("authorities :"+authorities);
        return authorities;
    }
}
Authentication Provider実現クラス:
/**
 * Created by fjc on 2018-04-23.
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private CustomUserDetailsService userService;

    /**
     *        
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        System.out.println("          :" + password);
        System.out.println("      :" + MD5.MD5(password));
        UserDetails user = userService.loadUserByUsername(username);

        //         
        System.out.println("  CustomUserDetailsService ,              :" + user.getPassword());
        if (!user.getPassword().equals(MD5.MD5(password))) {
            throw new DisabledException("Wrong password.");
        }

        Collection extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class> arg0) {
        return true;
    }
}