一、先看下DaoAuthenticationProvider的认证过程

【Spring Boot】Spring Boot之整合Spring security实现JWT权限认证

 

1、从读取用户名和密码开始的身份验证Filter将一个UsernamePasswordAuthenticationToken传递给由ProviderManager实现的AuthenticationManager。

2、ProviderManager被配置为使用DaoAuthenticationProvider类型的AuthenticationProvider。

3、第三个DaoAuthenticationProvider从UserDetailsService中查找用户详细信息。

4、DaoAuthenticationProvider使用PasswordEncoder验证上一步返回的用户详细信息上的密码。

5、当身份验证成功时,返回的身份验证类型为UsernamePasswordAuthenticationToken,其主体是已配置的UserDetailsService返回的用户详细信息。最终,返回的UsernamePasswordAuthenticationToken将由身份验证过滤器在securitycontext中设置。

二、过程分析

1)登陆认证
项目中,我们如何实现这个过程

1、自定义UserDetailsService(用于提供用户信息一般通过用户名从数据库查询)

/**
 * 用户登录认证信息查询
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TUserDAO tUserDAO;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser user = tUserDAO.getByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        // 用户权限列表,根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比,决定是否可以调用接口
//        Set<String> permissions = sysUserService.findPermissions(user.getName());
        Set<String> permissions = new HashSet<>();
        permissions.add("query");
        List<GrantedAuthority> grantedAuthorities = permissions.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
        return new JwtUserDetails(user.getName(), user.getPassword(), user.getSalt(), user.getAccountType(), grantedAuthorities);
    }
}
View Code

相关文章: