看了UserDetails这个接口。翻译过来是这么描述的

 

他是一个接口,并不是一个类。

那么登录的对象肯定要存在一个类中。翻看以前利用SpringBoot项目中做的登录的笔记。发现所有接收到和查询到的登录信息都保存在SpringSecurity提供的User对象中。这个接口是这样实现的

//将查询到的结果放入UserDetails中
UserDetails userDetails= org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(arr)
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .build();

实现他的是个User类。

那么我可以理解成,登录之后,根据登录的用户名和密码,查询到的对应用户信息和权限信息。都保存在SpringSecurity提供的User类中。

而在User类中,确实有一个builder方法,他的返回值是UserBuilder。我在向下翻阅User类的时候看到了UserBuilder类。他是这样的。

我就把他理解成一个静态的内部类。应该是没错。而这个类的注解,翻译过来是这样的。

 用户名和密码不用解释什么。

先看下权限,authorities。他是个集合。但是看authorities重载了很多方法。有一个方法参数是权限名称的字符串数组

 但是return返回值中。authorites的方法参数是AuthorityUtils.createAuthorityList(方法参数)

那么我继续看AuthorityUtils这个类做了啥?

 他把方法参数中的字符串数组进行了遍历并将遍历的结果放到了创建的List<GrantedAuthority>集合中。返回对象时List<GrantedAuthority>集合。

		/**
		 * Populates the authorities. This attribute is required.
		 *
		 * @param authorities the authorities for this user (i.e. ROLE_USER, ROLE_ADMIN,
		 * etc). Cannot be null, or contain null values
		 * @return the {@link UserBuilder} for method chaining (i.e. to populate
		 * additional attributes for this user)
		 * @see #roles(String...)
		 */
		public UserBuilder authorities(String... authorities) {
			return authorities(AuthorityUtils.createAuthorityList(authorities));
		}

但是看他的返回值 是个UserBuilder 但是return前面的方法是这个内部类其他重载的方法。看看这个另一个重载的authorites方法是哪一个,并且做了啥?按住ctrl点方法名可以跳转到所用的方法上。是这个。

		/**
		 * Populates the authorities. This attribute is required.
		 *
		 * @param authorities the authorities for this user. Cannot be null, or contain
		 * null values
		 * @return the {@link UserBuilder} for method chaining (i.e. to populate
		 * additional attributes for this user)
		 * @see #roles(String...)
		 */
		public UserBuilder authorities(Collection<? extends GrantedAuthority> authorities) {
			this.authorities = new ArrayList<>(authorities);
			return this;
		}

它的方法参数是Collection的集合。而List是继承了Collection。是Collection的子类接口。

 而List<GrantedAuthority>作为方法参数传递进来。new一个新的List对象赋值给authorities变量。最后返回给当前对象的引用。

GrantedAuthority 其实也是一个接口 里面只有一个String getAuthority();

其实饶了一大圈,就是把权限的String类型数组,转换为List<String>的集合。

再说说 accountLocked这个方法。 这个方法的默认值为false。其实这地方有点绕。

最开始,user.getLocked()这个值是0.因为在数据库表中存储的就是0。

这个方法的方法参数中,如果方法参数中的值为true。账户就是被锁定的

如果方法参数中的值为false,那么账户就不是被锁定的。

那么,我在方法参数中做判断,判断user.getLocked()这个值 让他==1  就是0==1 肯定为false为false那么账户就没有被锁定。

再看看disabled这个方法。

如果方法参数里面的值为true,那么这个账户就是被禁用状态。

如果方法参数里面的值为false 那么这个账户就是没有被禁用状态

user.getEnabled()这个值是从数据库中的到的值,它的值为1

在方法参数中判断 让它的值为false 那么他就不会被禁用, 那么方法参数就是

user.getEnabled()==0  即为 1==0 那么结果为false。就是账户没有被禁用。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐