Spring Security认证之用户定义
创始人
2024-01-30 06:33:59

本文内容来自王松老师的《深入浅出Spring Security》,自己在学习的时候为了加深理解顺手抄录的,有时候还会写一些自己的想法。

        在前面的案例中,我们登陆的用户信息是基于配置文件来配置的,其本质上是基于内存来实现的。但是在实际的开发中这种方式是不可取的,实际开发中都是要将用户信息存储在数据库中的。

        Spring Security支持多种用户定义的方式,接下来我们逐个看下这些定意思方式。通过前面的学习我们配置好UserDetailsService,将UserDetailsService配置给AuthenticationManagerBuilder,系统在将UserDetailsService提供给AuthentncationProvider使用即可。

基于内存(InMemoryUserDetailsManager)

        前面的案例中我们是在配置文件中配置用户的信息,实际上也是也是基于内存。只是没有将InMemoryUserDetailsManager类明确抽出来自定义,现在我们通过自定义InMemoryUserDetailsManager来看一下基于内存如何自定义。

        重写WebSecurityConfigurerAdapter类的configure(AuthenticationManagerBuilder auth)方法,内容如下:

    @Overrideprotected 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

        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 = ?";//省略。。。。
}

基于数据库(自定义实现UserDetailsService,基于MyBatis

        使用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.bootmybatis-spring-boot-starter2.1.3mysqlmysql-connector-java8.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<>();@Overridepublic Collection getAuthorities() {List authorities = new ArrayList<>();for (Role role : roles) {authorities.add(new SimpleGrantedAuthority(role.getName()));}return authorities;}@Overridepublic String getPassword() {return password;}@Overridepublic String getUsername() {return username;}@Overridepublic boolean isAccountNonExpired() {return accountNonExpired;}@Overridepublic boolean isAccountNonLocked() {return accountNonLocked;}@Overridepublic boolean isCredentialsNonExpired() {return credentialsNonExpired;}@Overridepublic 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 {@Autowiredprivate UserMapper userMapper;@Overridepublic 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**/*.xmlsrc/main/resources

        最后一步,在Spring Security的配置类中将我们自定义的UserDetailsService添加进去:

/*** @author tlh* @date 2022/11/16 21:11*/
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Overrideprotected 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();}@Overrideprotected 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() {@Overridepublic 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);}};}
}

        至此,整个配置工作就算完成了。接下来启动项目,利用数据库中添加的用户进行登录测试,就可以登录成功了。

上一篇:良好的言行

下一篇:祝彼此天天开心

相关内容

热门资讯

埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
安徒生童话有哪些 安徒生童话的... 从德国汉堡港乘轮船渡波罗的海抵丹麦王国,就到了安徒生的祖邦。安徒生(1805-1875)以童话作品闻...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...
世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
安徒生童话有哪些 安徒生童话的... 从德国汉堡港乘轮船渡波罗的海抵丹麦王国,就到了安徒生的祖邦。安徒生(1805-1875)以童话作品闻...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...