Spring security 自定义密码验证(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/f1370335844/article/details/80084085

搞了好几天,大概总结下。我找到的自定义密码验证有两种方式,按照网上的去写,确实能做到密码验证,但是密码对不上,抛出BadCredentialsException,并不能阻止用户进入权限页面,感觉好像Spring Security对抛出的BadCredentialsException没处理还是咋的,就是没反应,最后改为抛出DisabledException,Spring Security才反应正常,正常重定向到指定的密码错误地址。

本文先介绍第一种,实现AuthenticationProvider,或者去实现AuthenticationProvider的实现类,如DaoAuthenticationProvider都是可以的。

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");
    }

}

UserDetailsService实现类:

/**
 * 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<GrantedAuthority> getGrantedAuthorities(int userid){
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        List<UserProfile> 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;
    }
}

AuthenticationProvider实现类:

/**
 * 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;
    }
}



猜你喜欢

转载自blog.csdn.net/f1370335844/article/details/80084085
今日推荐