springsecurity-查询数据库认证

  核心代码如下:

@Service
public class MyUserDatailService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<Users> wrapper = new QueryWrapper<>();

        wrapper.eq("username", username);

        Users users = usersMapper.selectOne(wrapper);

        if(users == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");

        return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){

        return new BCryptPasswordEncoder();
    }
}

   其实通过在loadUserByUsername()的代码我们可以知道,不需要我们亲手去校验表单的用户名和密码和数据库的是否一样,我们只需要在该方法里,查询数据库的用户信息,把他交给springsecurity就行了。

posted @ 2021-02-03 11:36  爱编程DE文兄  阅读(255)  评论(0编辑  收藏  举报