security认证授权系统添加自定义用户登录
-
spring-security.xml配置,对登录认证管理器进行配置
<!--配置登录认证管理器-->
<security:authentication-manager>
<!--提供服务类 去数据库查询账户密码-->
<security:authentication-provider user-service-ref="userService">
</security:authentication-provider>
</security:authentication-manager>
- user-service-ref="userService"为IOC容器service层的bean对象
- 编写与数据库sysuser表对应的实体类(类名不要用User,因为security有一个实体类就是User)
- service接口继承UserDetailsService(security框架的接口)
public interface UserService extends UserDetailsService {
}
- serviceImpl实现UserDetailsService接口的抽象方法 public UserDetails loadUserByUsername(String username);
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//根据用户名获取用户对象
SysUser sysUser = userDao.findByUsername(username);
System.out.println("sysUser:" + sysUser);
if (sysUser != null) {
//创建角色集合对象
Collection<GrantedAuthority> authorities = new ArrayList<>();
//创建临时角色对象
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
//对象添加到集合中
authorities.add(grantedAuthority);
User user = new User(sysUser.getUsername(), "{noop}" + sysUser.getPassword(), authorities);
System.out.println("user:" + user);
return user;
}
return null;
}
}
- dao层
public interface UserDao {
//根据用户名查询用户对象
@Select("select * from sys_user where username = #{username}")
SysUser findByUsername(String username) ;
}
![](https://i-blog.csdnimg.cn/blog_migrate/0cfcac96d51370d6fe287a091a0cf915.png)