本文内容来自王松老师的《深入浅出Spring Security》,自己在学习的时候为了加深理解顺手抄录的,有时候还会写一些自己的想法。
在前面的案例中,我们登陆的用户信息是基于配置文件来配置的,其本质上是基于内存来实现的。但是在实际的开发中这种方式是不可取的,实际开发中都是要将用户信息存储在数据库中的。
Spring Security支持多种用户定义的方式,接下来我们逐个看下这些定意思方式。通过前面的学习我们配置好UserDetailsService,将UserDetailsService配置给AuthenticationManagerBuilder,系统在将UserDetailsService提供给AuthentncationProvider使用即可。
前面的案例中我们是在配置文件中配置用户的信息,实际上也是也是基于内存。只是没有将InMemoryUserDetailsManager类明确抽出来自定义,现在我们通过自定义InMemoryUserDetailsManager来看一下基于内存如何自定义。
重写WebSecurityConfigurerAdapter类的configure(AuthenticationManagerBuilder auth)方法,内容如下:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
inMemoryUserDetailsManager.createUser(
User
.withUsername("tlh")
.password("{noop}123456")
.authorities("admin", "users")
.build());
auth.userDetailsService(inMemoryUserDetailsManager);
}
首先创建一个InMemoryUserDetailsManager的实例,调用该实例的createUser方法来创建用户,我们设置了用户的账户名、密码、设置了用户的权限。注意的是这里采用明文的方式存储密码,就是在密码的前面添加了{noop}。如果没有配置的话,系统会提示没有匹配到PasswordEncoder。
JdbcUserDetailsManager也是Spring Security提供的一个基于数据库保存用户信息的一种策略。但是我们一般也不会使用,因为使用JdbcUserDetailsManager的话有一定的局限性,其已经写好了sql,所以一般在实际开发中也不会使用。见JdbcUserDetailsManager类中的定义:
public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsManager, GroupManager {
public static final String DEF_CREATE_USER_SQL = "insert into users (username, password, enabled) values (?,?,?)";
public static final String DEF_DELETE_USER_SQL = "delete from users where username = ?";
public static final String DEF_UPDATE_USER_SQL = "update users set password = ?, enabled = ? where username = ?";
public static final String DEF_INSERT_AUTHORITY_SQL = "insert into authorities (username, authority) values (?,?)";
public static final String DEF_DELETE_USER_AUTHORITIES_SQL = "delete from authorities where username = ?";
public static final String DEF_USER_EXISTS_SQL = "select username from users where username = ?";
public static final String DEF_CHANGE_PASSWORD_SQL = "update users set password = ? where username = ?";
public static final String DEF_FIND_GROUPS_SQL = "select group_name from groups";
public static final String DEF_FIND_USERS_IN_GROUP_SQL = "select username from group_members gm, groups g where gm.group_id = g.id and g.group_name = ?";
public static final String DEF_INSERT_GROUP_SQL = "insert into groups (group_name) values (?)";
public static final String DEF_FIND_GROUP_ID_SQL = "select id from groups where group_name = ?";
public static final String DEF_INSERT_GROUP_AUTHORITY_SQL = "insert into group_authorities (group_id, authority) values (?,?)";
public static final String DEF_DELETE_GROUP_SQL = "delete from groups where id = ?";
public static final String DEF_DELETE_GROUP_AUTHORITIES_SQL = "delete from group_authorities where group_id = ?";
public static final String DEF_DELETE_GROUP_MEMBERS_SQL = "delete from group_members where group_id = ?";
public static final String DEF_RENAME_GROUP_SQL = "update groups set group_name = ? where group_name = ?";
public static final String DEF_INSERT_GROUP_MEMBER_SQL = "insert into group_members (group_id, username) values (?,?)";
public static final String DEF_DELETE_GROUP_MEMBER_SQL = "delete from group_members where group_id = ? and username = ?";
public static final String DEF_GROUP_AUTHORITIES_QUERY_SQL = "select g.id, g.group_name, ga.authority from groups g, group_authorities ga where g.group_name = ? and g.id = ga.group_id ";
public static final String DEF_DELETE_GROUP_AUTHORITY_SQL = "delete from group_authorities where group_id = ? and authority = ?";
protected final Log logger = LogFactory.getLog(this.getClass());
private String createUserSql = "insert into users (username, password, enabled) values (?,?,?)";
private String deleteUserSql = "delete from users where username = ?";
private String updateUserSql = "update users set password = ?, enabled = ? where username = ?";
private String createAuthoritySql = "insert into authorities (username, authority) values (?,?)";
private String deleteUserAuthoritiesSql = "delete from authorities where username = ?";
private String userExistsSql = "select username from users where username = ?";
private String changePasswordSql = "update users set password = ? where username = ?";
private String findAllGroupsSql = "select group_name from groups";
private String findUsersInGroupSql = "select username from group_members gm, groups g where gm.group_id = g.id and g.group_name = ?";
private String insertGroupSql = "insert into groups (group_name) values (?)";
private String findGroupIdSql = "select id from groups where group_name = ?";
private String insertGroupAuthoritySql = "insert into group_authorities (group_id, authority) values (?,?)";
private String deleteGroupSql = "delete from groups where id = ?";
private String deleteGroupAuthoritiesSql = "delete from group_authorities where group_id = ?";
private String deleteGroupMembersSql = "delete from group_members where group_id = ?";
private String renameGroupSql = "update groups set group_name = ? where group_name = ?";
private String insertGroupMemberSql = "insert into group_members (group_id, username) values (?,?)";
private String deleteGroupMemberSql = "delete from group_members where group_id = ? and username = ?";
private String groupAuthoritiesSql = "select g.id, g.group_name, ga.authority from groups g, group_authorities ga where g.group_name = ? and g.id = ga.group_id ";
private String deleteGroupAuthoritySql = "delete from group_authorities where group_id = ? and authority = ?";
//省略。。。。
}
使用MyBatis做持久化目前是大多数企业应用采用的方案,Spring Security结合MyBatis可以灵活的制定用户表以及角色表。
首先需要设计三张表,分别是用户表、角色表、以及用户和角色关联表。三张表关系入下图:
用户和角色的关系是多对多的关系,我们使用user_role将两者关联起来。
数据库表脚本如下:
//创建表
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`nameZh` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`enabled` tinyint(1) DEFAULT NULL,
`accountNonExpired` tinyint(1) DEFAULT NULL,
`accountNonLocked` tinyint(1) DEFAULT NULL,
`credentialsNonExpired` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) DEFAULT NULL,
`rid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `uid` (`uid`),
KEY `rid` (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//插入测试数据
INSERT INTO `role` (`id`, `name`, `nameZh`)
VALUES
(1,'ROLE_dba','数据库管理员'),
(2,'ROLE_admin','系统管理员'),
(3,'ROLE_user','用户');
INSERT INTO `user` (`id`, `username`, `password`, `enabled`,
`accountNonExpired`, `accountNonLocked`, `credentialsNonExpired`)
VALUES
(1,'root','{noop}123',1,1,1,1),
(2,'admin','{noop}123',1,1,1,1),
(3,'sang','{noop}123',1,1,1,1);
INSERT INTO `user_role` (`id`, `uid`, `rid`)
VALUES
(1,1,1),
(2,1,2),
(3,2,2),
(4,3,3);
在项目的bom依赖中引入MyBatis Plus和mySql的依赖:
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
mysql
mysql-connector-java
8.0.16
在配置文件中配置数据库基本连接信息:
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/spring_security_user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
接下来创建用户和角色类:
/**
* @author tlh
* @date 2022/11/17 23:47
*/
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean accountNonExpired;
private Boolean accountNonLocked;
private Boolean credentialsNonExpired;
private List roles = new ArrayList<>();
@Override
public Collection extends GrantedAuthority> getAuthorities() {
List authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
//省略get/set方法
}
/**
* @author tlh
* @date 2022/11/17 23:47
*/
public class Role {
private Integer id;
private String name;
private String nameZh;
//省略get/set方法
}
接下来自定义UserDetailsService:
/**
* @author tlh
* @date 2022/11/17 23:52
*/
@Component
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
user.setRoles(userMapper.getRolesByUid(user.getId()));
return user;
}
}
为了方便测试我们将UserMapper.xml和UserMapper接口放在相同的包下。
为了防止maven打包是忽略掉xml文件,我们还需要在pom.xml中添加如下配置:
src/main/java
**/*.xml
src/main/resources
最后一步,在Spring Security的配置类中将我们自定义的UserDetailsService添加进去:
/**
* @author tlh
* @date 2022/11/16 21:11
*/
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/doLogin")
.successHandler(getAuthenticationSuccessHandler())
.failureUrl("/login.html")
.usernameParameter("uname")
.passwordParameter("passwd")
.permitAll()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//内存方式
// InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
// inMemoryUserDetailsManager.createUser(
// User
// .withUsername("tlh")
// .password("{noop}123456")
// .authorities("admin", "users")
// .build());
// auth.userDetailsService(inMemoryUserDetailsManager);
//数据库方式
auth.userDetailsService(userDetailsService);
}
AuthenticationSuccessHandler getAuthenticationSuccessHandler() {
return new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
Map respMap = new HashMap<>(2);
respMap.put("code", "200");
respMap.put("msg", "登录成功");
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(respMap);
response.getWriter().write(jsonStr);
}
};
}
}
至此,整个配置工作就算完成了。接下来启动项目,利用数据库中添加的用户进行登录测试,就可以登录成功了。